yoo
yoo

Reputation: 491

How can I randomly sample binomial thing?

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.

Upvotes: 2

Views: 102

Answers (4)

ThomasIsCoding
ThomasIsCoding

Reputation: 101014

We can use bitwAnd + sample

bitwAnd(sample(10), 1)

Upvotes: 3

Allan Cameron
Allan Cameron

Reputation: 173783

A shortcut would be:

sample(10) %/% 6
#> [1] 0 0 0 1 1 0 0 1 1 1

Upvotes: 2

George Savva
George Savva

Reputation: 5306

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

Upvotes: 5

dcarlson
dcarlson

Reputation: 11046

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

Upvotes: 4

Related Questions