match_and_reorder.Rd
Function to match a vector of values against another vector and reorder the original vector based on the matching indices.
match_and_reorder(x, values, y = NULL)
A vector.
A vector containing the values to match
against in x
.
An optional vector matching in length to x
to reorder - otherwise the function returns the indices
for reordering.
Either a vector of indices for reordering or the
reordered output from the input y
.
x <- rep( LETTERS[1:3], 3 )
values <- c( 'C', 'B', 'A' )
y <- rep( 1:3, 3 )
match_and_reorder( x, values, y )
#> [1] 3 3 3 2 2 2 1 1 1
set.seed( 111 ) # For reproducibility
# Example data frame
dtf_example <- data.frame(
X = rep( 1:4, each = 2 ),
Y = round( rnorm( 8 ), 2 )
)
# Resample with replacement from 'X'
shuffled_x <- sample( 1:4, size = 4, replace = TRUE )
# Create a reordered data frame based on the resampled values
dtf_shuffled <- data.frame(
X = match_and_reorder( dtf_example$X, shuffled_x, dtf_example$X ),
Y = match_and_reorder( dtf_example$X, shuffled_x, dtf_example$Y )
)