Back
I would like to randomly reorganize the order of the numbers in a vector, in a simple one-line command?
My particular vector V has 150 entries for each value from 1 to 10:
V <- rep(1:10, each=150)
To randomize a vector, you can use the sample() function from the base package, as follows:
V <- rep(1:10, each=150)sample(V)[1] 2 9 10 6 3 6 8 4 1 7 8 1 10 5 2 8 1 10 6 10 9 6 3 4 8 6 1 9 9 8 7 [32] 7 4 3 7 5 5 2 1 10 4 8 9 1 1 9 10 8 4 5 9 7 6 9 6 4 4 10 6 7 6 6 [63] 2 2 1 3 7 5 6 8 1 2 8 8 4 4 10 3 10 3 9 6 8 7 5 5 8 4 1 5 2 5 1 [94] 5 3 8 9 8 6 8 4 7 5 6 1 9 2 7 9 5 10 3 6 5 1 3 4 5 8 10 2 7 4 1 [125] 5 3 3 9 3 9 3 7 2 1 9 2 3 3 4 3 1 3 6 8 10 4 6 3 7 4 2 2 5 7 10 [156] 4 2 1 10 7 5 4 10 10 3 5 1 9 9 1 1 5 4 8 4 8 1 9 9 5 4 10 5 5 4
sample(V)
[1] 2 9 10 6 3 6 8 4 1 7 8 1 10 5 2 8 1 10 6 10 9 6 3 4 8 6 1 9 9 8 7
[32] 7 4 3 7 5 5 2 1 10 4 8 9 1 1 9 10 8 4 5 9 7 6 9 6 4 4 10 6 7 6 6
[63] 2 2 1 3 7 5 6 8 1 2 8 8 4 4 10 3 10 3 9 6 8 7 5 5 8 4 1 5 2 5 1
[94] 5 3 8 9 8 6 8 4 7 5 6 1 9 2 7 9 5 10 3 6 5 1 3 4 5 8 10 2 7 4 1
[125] 5 3 3 9 3 9 3 7 2 1 9 2 3 3 4 3 1 3 6 8 10 4 6 3 7 4 2 2 5 7 10
[156] 4 2 1 10 7 5 4 10 10 3 5 1 9 9 1 1 5 4 8 4 8 1 9 9 5 4 10 5 5 4
31k questions
32.8k answers
501 comments
693 users