Reputation: 2310
I would like to generate a random binary combination (row order) in my dataframe df
:
bin
2
2
2
2
3
2
3
2
In this example I intend to generate 6 times 0
(the same number of 2
) and two times 1
(the same number of 3
). I expect something like that:
bin
0
0
1
0
0
1
0
0
Any ideas? Thank you
Upvotes: 0
Views: 50
Reputation: 206536
So given a vector bin
bin<-c(2,2,2,2,3,2,3,2)
You would like to create a new vector that contains the same number of 0's as the number of 2's in bin
, and the same number of 1's as the number of 3's in bin
. Assuming that's correct, then
sample(rep(0:1, table(bin)))
Should do the trick. Here are the results of running that command several times:
# 0 0 0 0 1 1 0 0
# 0 0 0 1 0 0 1 0
# 0 0 0 1 0 0 1 0
# 0 0 1 0 1 0 0 0
Upvotes: 3