Lily
Lily

Reputation: 37

Permutation position of numbers in R

I'm looking for a function in R which can do the permutation. For example, I have a vector with five 1 and ten 0 like this:

> status=c(rep(1,5),rep(0,10))
> status
 [1] 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0

Now I'd like to randomly permute the position of these numbers but keep the same number of 0 and 1 in vector and to get new series of number, for example to get something like this:

1 1 0 1 0 1 0 0 0 0 0 1 0 0 0

or

1 0 0 0 0 0 0 1 1 0 0 1 0 1 0

I found the function sample() can help us to sample, but the number of 1 and 0 is not the same each time. Do you know how can I do this with R? Thanks in advance.

Upvotes: 1

Views: 122

Answers (1)

akrun
akrun

Reputation: 887901

We can use sample

sample(status)
#[1] 1 0 0 1 0 0 1 0 0 0 0 1 0 1 0
sample(status)
#[1] 0 0 0 0 1 1 0 0 1 1 0 0 0 1 0

If we use sample to return the entire vector, it will do the permutation and give the frequency count same for each of the unique elements

colSums(replicate(5, sample(status)))
#[1] 5 5 5 5 5

i.e. we get 5 one's in each of the sampling. So, the remaining 0's would be 10.

Upvotes: 2

Related Questions