roll_elements {rearrr}R Documentation

Roll elements

Description

[Experimental]

Rolls positions of elements.

Example:

Rolling c(1, 2, 3, 4, 5) with `n = 2` becomes:

c(3, 4, 5, 1, 2)

roll_elements_vec() takes and returns a vector.

Should not be confused with roll_values(), which changes the values of the elements and wraps to a given range.

Usage

roll_elements(
  data,
  cols = NULL,
  n = NULL,
  n_fn = NULL,
  n_col_name = ".n",
  overwrite = FALSE,
  ...
)

roll_elements_vec(data, n = NULL, n_fn = NULL, ...)

Arguments

data

vector or data.frame to roll elements of. When a data.frame is grouped, the rolling is applied group-wise.

cols

Names of columns in `data` to roll. If NULL, the index is rolled and used to reorder `data`.

N.B. only used when `data` is a data.frame.

n

Number of positions to roll. A positive number rolls left/up. A negative number rolls right/down.

n_fn

Function to find `n`. Useful when `data` is a grouped data.frame and `n` should depend on the rows in the group.

Input: Each specified vector/column in `data` is passed to the function as a separate argument.

Output: It should return either a vector with one integer-like scalar per column or a single integer-like scalar to use for all columns.

Can be created with create_n_fn(). See also median_index() and quantile_index().

n_col_name

Name of new column with the applied `n` values. If NULL, no column is added.

overwrite

Whether to allow overwriting of columns with the same name as `n_col_name`. (Logical)

...

Extra arguments for `n_fn`.

Value

Rolled `data`.

Author(s)

Ludvig Renbo Olsen, r-pkgs@ludvigolsen.dk

See Also

Other roll functions: roll_values()

Other rearrange functions: center_max(), center_min(), closest_to(), furthest_from(), pair_extremes(), position_max(), position_min(), rev_windows(), shuffle_hierarchy(), triplet_extremes()

Examples

# Attach packages
library(rearrr)
library(dplyr)

# Roll vector left
roll_elements(1:10, n = 2)

# Roll vector right and return the vector
roll_elements_vec(1:10, n = -2)

# Roll vector left by median index (rounded to 6)
roll_elements(3:12, n_fn = median_index)

# Roll vector right by median value (rounded to 8)
roll_elements(3:12, n_fn = create_n_fn(median, negate = TRUE))

# Pass extra arguments (here 'prob') to 'n_fn' via '...'
roll_elements(
  1:10,
  n_fn = quantile_index,
  prob = 0.2
)

#
# Roll data.frame
#

# Set seed
set.seed(1)

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

# Roll rows left/up
roll_elements(df, n = 2)

# Roll rows right/down
roll_elements(df, n = -2)

# Roll 'x' column right/down
roll_elements(df, cols = "x", n = -2)

# Roll rows right by median index in each group
# Specify 'negate' for the 'median_index' function
roll_elements(
  df %>% dplyr::group_by(g),
  n_fn = median_index,
  negate = TRUE
)

[Package rearrr version 0.3.4 Index]