Mark Miller
Mark Miller

Reputation: 13123

binomial simulation inside an if-else statement

I am trying to create some data. First I want to flip 40 fair coins. For each coin that lands heads, or 1, I want to flip another fair coin.

I thought that using rbinom inside an ifelse statement would work, but I am getting what seem like odd results.

Here is my code where aa represents the results of flipping the first 40 coins and cc I thought represents the results of flipping a second coin for each coin in aa that landed heads.

I repeat the ifelse statement several times below and get one of two results. The first result for cc matches that of aa and the second result is all 0's. These results are perplexing. Thank you for any advice or explanation of what is happening.

set.seed(1234)

aa <- rbinom(40, 1, 0.5) ; aa
# [1] 0 1 1 1 1 1 0 0 1 1 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 0 1 1
cc <- ifelse(aa == 1, rbinom(1, 1, 0.5), 0) ; cc
# [1] 0 1 1 1 1 1 0 0 1 1 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 0 1 1
cc <- ifelse(aa == 1, rbinom(1, 1, 0.5), 0) ; cc
# [1] 0 1 1 1 1 1 0 0 1 1 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 0 1 1
cc <- ifelse(aa == 1, rbinom(1, 1, 0.5), 0) ; cc
# [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
cc <- ifelse(aa == 1, rbinom(1, 1, 0.5), 0) ; cc
# [1] 0 1 1 1 1 1 0 0 1 1 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 0 1 1
cc <- ifelse(aa == 1, rbinom(1, 1, 0.5), 0) ; cc
# [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
cc <- ifelse(aa == 1, rbinom(1, 1, 0.5), 0) ; cc
# [1] 0 1 1 1 1 1 0 0 1 1 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 0 1 1

Upvotes: 1

Views: 835

Answers (2)

Scott Ritchie
Scott Ritchie

Reputation: 10543

It appears that R is really lazy when it comes to evaluating the ifelse statement, so it is only calling rbinom(1,1,0.5) once!

cc <- ifelse(aa == 1, rbinom(1,1,0.5), 0) 

is the equivalent of:

cc <- aa
cc[cc == 1] <- rbinom(1,1,0.5)

I had a play around, and the only way to get R to call rbinom multiple times is to do it in a for loop:

set.seed(1234)
aa <- rbinom(40, 1, 0.5); aa
# [1] 0 1 1 1 1 1 0 0 1 1 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 0 1 1
cc <- aa
for (i in seq_along(cc)) {
    cc[i] <- ifelse(cc[i] == 1, rbinom(1,1,0.5), 0)
}
cc
#  [1] 0 1 1 0 1 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 1 0

Upvotes: 1

Thomas
Thomas

Reputation: 44555

Your current code is probably not ideal because a "tails" flip and no flip (because aa==0) result in the same output (0). Also, your second flip is only providing one flip rather than a vector of flips, thus the reason why all of your cc results are either the same sequence of 0's and 1's or all 0 (depending on whether the second flip is 1 or 0, respectively). Try:

cc <- ifelse(aa == 1, rbinom(length(aa), 1, 0.5), NA); cc

Upvotes: 3

Related Questions