98

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)
smci
  • 32,567
  • 20
  • 113
  • 146
user1723765
  • 6,179
  • 18
  • 57
  • 85
  • 9
    The answers here rightly point your toward `sample`. You might want to check out the warnings [here](http://stackoverflow.com/a/13732373/1003565) for some dangers that go along with just using sample as is. – Dason Dec 07 '12 at 15:32
  • @Dason: the tl;dr is as long as the vector length is guaranteed to be >1, it works. – smci Apr 25 '18 at 00:35
  • 1
    @smci The tl;Dr is that it's dangerous because one gets comfortable with it and then when it finally is of length 1 it bites you. – Dason Apr 25 '18 at 02:06
  • @Dason I had read that, but noone's yet modified `base::sample` to force use of `seq_along`. Also I don't see where `sample/sample.int` call `base::seq()` anyway? – smci Apr 25 '18 at 06:27

2 Answers2

156

Yes.

sample(V)

From ?sample:

For ‘sample’ the default for ‘size’ is the number of items inferred from the first argument, so that ‘sample(x)’ generates a random permutation of the elements of ‘x’ (or ‘1:x’).

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • How can I shuffle [1,1, 2, 2, 2, 2, 3, 3, 4, 5, 5, 5] such that I get something like this: [5, 5, 3, 3, 3, 3, 1, 1, 2, 4, 4, 4]? such that each element could randomly change to another but with keeping the number of each element constant? – Rotail Oct 22 '16 at 03:30
  • 2
    @Rotail: this already does what you want; the `size` argument of `sample` defaults to `size <- length(x)`. (Type `sample` to see the code that does this.) – smci Apr 25 '18 at 00:38
  • yup! Thank you! – Rotail Apr 25 '18 at 13:23
25

Use sample function

V<-rep(1:10, each=150)

set.seed(001) # just to make it reproducible
sample(V)
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138