Randomizing order

Problem

You want to randomize the order of a data structure.

Solution

  1. # Create a vector
  2. v <- 11:20
  3. # Randomize the order of the vector
  4. v <- sample(v)
  5. # Create a data frame
  6. data <- data.frame(label=letters[1:5], number=11:15)
  7. data
  8. #> label number
  9. #> 1 a 11
  10. #> 2 b 12
  11. #> 3 c 13
  12. #> 4 d 14
  13. #> 5 e 15
  14. # Randomize the order of the data frame
  15. data <- data[sample(1:nrow(data)), ]
  16. data
  17. #> label number
  18. #> 5 e 15
  19. #> 2 b 12
  20. #> 4 d 14
  21. #> 3 c 13
  22. #> 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.