Randomizing order
Problem
You want to randomize the order of a data structure.
Solution
# Create a vector
v <- 11:20
# Randomize the order of the vector
v <- sample(v)
# Create a data frame
data <- data.frame(label=letters[1:5], number=11:15)
data
#> label number
#> 1 a 11
#> 2 b 12
#> 3 c 13
#> 4 d 14
#> 5 e 15
# Randomize the order of the data frame
data <- data[sample(1:nrow(data)), ]
data
#> label number
#> 5 e 15
#> 2 b 12
#> 4 d 14
#> 3 c 13
#> 1 a 11
Notes
To make a randomization repeatable, you should set the seed for the random number generator. See ../../Numbers/Generating random numbers and ../../Numbers/Generating repeatable sequences of random numbers for more information.
当前内容版权归 cookbook-r.com 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 cookbook-r.com .