# Attach packages
library(rearrr)
library(dplyr)
has_ggplot <- require(ggplot2) # Attach if installed
# Set seed
set.seed(1)
# Create a data frame
df <- data.frame(
"x" = runif(20),
"y" = runif(20),
"g" = rep(1:4, each = 5)
)
# Calculate angles in the two dimensions (x and y)
# With the origin at x=0.5, y=0.5
df_angles <- angle(
data = df,
x_col = "x",
y_col = "y",
origin = c(0.5, 0.5)
)
df_angles
# Plot points with degrees
# Degrees are measured counterclockwise around the
# positive side of the x-axis
if (has_ggplot){
df_angles %>%
ggplot(aes(x = x, y = y, color = .degrees)) +
geom_segment(aes(x = 0.5, xend = 1, y = 0.5, yend = 0.5), color = "magenta") +
geom_point() +
theme_minimal()
}
# Calculate angles to the centroid for each group in 'g'
angle(
data = dplyr::group_by(df, g),
x_col = "x",
y_col = "y",
origin_fn = centroid
)
Run the code above in your browser using DataLab