Learn R Programming

rearrr (version 0.3.4)

angle: Calculate the angle to an origin

Description

lifecycle::badge("experimental")

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.

Angles wheel

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.

Usage

angle(
  data,
  x_col = NULL,
  y_col = NULL,
  origin = NULL,
  origin_fn = NULL,
  degrees_col_name = ".degrees",
  origin_col_name = ".origin",
  overwrite = FALSE
)

Value

data.frame (tibble) with the additional columns (degrees and origin coordinates).

Arguments

data

data.frame or vector.

x_col

Name of x column in `data`. If NULL and `data` is a vector, the index of `data` is used. If `data` is a data.frame, it must be specified.

y_col

Name of y column in `data`. If `data` is a data.frame, it must be specified.

origin

Coordinates of the origin to calculate angle to. A scalar to use in all dimensions or a vector with one scalar per dimension.

N.B. Ignored when `origin_fn` is not NULL.

origin_fn

Function for finding the origin coordinates.

Input: Each column will be passed as a vector in the order of `cols`.

Output: A vector with one scalar per dimension.

Can be created with create_origin_fn() if you want to apply the same function to each dimension.

E.g. `create_origin_fn(median)` would find the median of each column.

Built-in functions are centroid(), most_centered(), and midrange()

degrees_col_name

Name of new column with the degrees.

origin_col_name

Name of new column with the origin coordinates. If NULL, no column is added.

overwrite

Whether to allow overwriting of existing columns. (Logical)

Author

Ludvig Renbo Olsen, r-pkgs@ludvigolsen.dk

See Also

Other measuring functions: distance(), vector_length()

Examples

Run this code
# 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