99

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)
4
  • 9
    The answers here rightly point your toward sample. You might want to check out the warnings here for some dangers that go along with just using sample as is.
    – Dason
    Dec 7, 2012 at 15:32
  • @Dason: the tl;dr is as long as the vector length is guaranteed to be >1, it works.
    – smci
    Apr 25, 2018 at 0: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, 2018 at 2: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, 2018 at 6:27

2 Answers 2

159

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’).

3
  • 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, 2016 at 3: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, 2018 at 0:38
  • yup! Thank you!
    – Rotail
    Apr 25, 2018 at 13:23
25

Use sample function

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

set.seed(001) # just to make it reproducible
sample(V)
2
  • 1
    replace=FALSE is the default value.
    – Ben Bolker
    Dec 7, 2012 at 15:25
  • this makes a 150 values from the original 1500 Dec 7, 2012 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.