| angle | R Documentation | 
Calculates the angle between each data point (x2, y2) and the origin (x1, y1) with:
atan2(y2 - y1, x2 - x1)
And converts to degrees [0-360), measured counterclockwise from the {x > x1, y = y1} line.
 
The origin can be supplied as coordinates or as a function that returns coordinates. The
latter can be useful when supplying a grouped data.frame and finding the angle to e.g. the centroid
of each group.
angle(
  data,
  x_col = NULL,
  y_col = NULL,
  origin = NULL,
  origin_fn = NULL,
  degrees_col_name = ".degrees",
  origin_col_name = ".origin",
  overwrite = FALSE
)
| data | 
 | 
| x_col | Name of x column in  | 
| y_col | Name of y column in  | 
| origin | Coordinates of the origin to calculate angle to.
A scalar to use in all dimensions
or a  N.B. Ignored when  | 
| origin_fn | Function for finding the origin coordinates. Input: Each column will be passed as a  Output: A  Can be created with  E.g.  Built-in functions are  | 
| degrees_col_name | Name of new column with the degrees. | 
| origin_col_name | Name of new column with the origin coordinates. If  | 
| overwrite | Whether to allow overwriting of existing columns. (Logical) | 
data.frame (tibble) with the additional columns (degrees and origin coordinates).
Ludvig Renbo Olsen, r-pkgs@ludvigolsen.dk
Other measuring functions: 
distance(),
vector_length()
# 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
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.