View source: R/roll_elements.R
| roll_elements | R Documentation |
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.
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, ...)
data |
|
cols |
Names of columns in N.B. only used when |
n |
Number of positions to roll. A positive number rolls left/up. A negative number rolls right/down. |
n_fn |
Function to find Input: Each specified Output: It should return either a Can be created with |
n_col_name |
Name of new column with the applied |
overwrite |
Whether to allow overwriting of columns with the
same name as |
... |
Extra arguments for |
Rolled `data`.
Ludvig Renbo Olsen, r-pkgs@ludvigolsen.dk
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()
# 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
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.