vector_length {rearrr}R Documentation

Calculate vector length(s)

Description

[Experimental]

Calculates vector lengths/magnitudes row- or column-wise with

sqrt(sum(x^2))

Where x is the vector to get the length/magnitude of.

Should not be confused with length(), which counts the elements.

Usage

vector_length(
  data,
  cols = NULL,
  by_row = is.data.frame(data),
  len_col_name = ".vec_len",
  overwrite = FALSE
)

Arguments

data

data.frame or vector.

cols

Names of columns in `data` to measure vector length of.

by_row

Whether to measure length of row vectors instead of column vectors. (Logical)

Note: Disable when `data` is a vector.

len_col_name

Name of new column with the row vector lengths when `data` is a data.frame and `by_row` is TRUE.

overwrite

Whether to allow overwriting of existing columns. (Logical)

Value

Vector length(s).

When `data` is a vector: scalar

When `data` is a data.frame and `by_row` is TRUE: `data` with an extra column with row vector lengths.

When `data` is a data.frame and `by_row` is FALSE: A data.frame with the summarized column vector lengths.

Author(s)

Ludvig Renbo Olsen, r-pkgs@ludvigolsen.dk

See Also

Other measuring functions: angle(), distance()

Examples

# Attach packages
library(rearrr)
library(dplyr)

# Set seed
set.seed(1)

# Create a data frame
df <- data.frame(
  "x" = runif(20),
  "y" = runif(20),
  "g" = rep(1:4, each = 5)
)

# Measure row-wise
vector_length(df, cols = c("x", "y"), by_row = TRUE)

# Measure column-wise
vector_length(df, cols = c("x", "y"), by_row = FALSE)

# By groups in 'g'
df %>%
  dplyr::group_by(g) %>%
  vector_length(cols = c("x", "y"), by_row = FALSE)

# Measure vector length of a vector
vector_length(c(1:10))

[Package rearrr version 0.3.4 Index]