Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomize a vector

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) 
like image 762
user1723765 Avatar asked Dec 07 '12 15:12

user1723765


People also ask

How do you shuffle a vector?

How to shuffle a std::vector in C++ A vector shuffle can be done in the Fisher-Yates shuffle algorithm. In this algorithm, a linear scan of a vector is done and then swap each element with a random element among all the remaining element, including the element itself.

How do you shuffle in C++?

The shuffle() function in C++ is a function in vector library. It is a function that will rearrange the elements of any range by placing the elements at random positions. To shuffle it uses a uniform random generator which helps in shuffling the elements.


2 Answers

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

like image 88
Ben Bolker Avatar answered Nov 16 '22 00:11

Ben Bolker


Use sample function

V<-rep(1:10, each=150)  set.seed(001) # just to make it reproducible sample(V) 
like image 34
Jilber Urbina Avatar answered Nov 16 '22 01:11

Jilber Urbina