3

For example, I want to randomly line the 0, 1 (50% respectively) 10 times. So, there should be five "0" and five "1".

But, when I used:

rbinom(10,1,0.5)

sometimes, it generates four "0" and six "1".

I noticed that the sample() function has also this issue.

There should be five "0" and five "1", and the order should be at random.

lovalery
  • 4,524
  • 3
  • 14
  • 28
yoo
  • 491
  • 3
  • 10

4 Answers4

6

sample will shuffle a vector randomly. So sample(rep(c(0,1),5)) is what you need.

George Savva
  • 4,152
  • 1
  • 7
  • 21
5

You need to use sample(), but this way:

b <- c(rep(0, 5), rep(1, 5))
sample(b)
#  [1] 1 0 1 1 0 0 1 0 0 1
sample(b)
#  [1] 0 1 1 1 0 1 0 0 0 1
sample(b)
#  [1] 0 0 0 1 1 1 0 1 0 1
sample(b)
#  [1] 0 1 0 0 1 0 1 1 0 1
dcarlson
  • 10,936
  • 2
  • 15
  • 18
3

A shortcut would be:

sample(10) %/% 6
#> [1] 0 0 0 1 1 0 0 1 1 1
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
3

We can use bitwAnd + sample

bitwAnd(sample(10), 1)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81