Reputation: 207
I am trying to generate a random number using rbinom()
with a binomial distribution. However, instead of generating a 0 or 1, I would like to replace the 0 with a value of 2. I have tried rbinom(n=1, size = 1, prob = 0.75) + 1
, and then changing values of 2 into values of 1 and vice versa in a data frame, but I'm struggling to work out a solution that doesn't involve having to do that. I thought about using sample.int()
in a similar manner but also struggled with this.
I would like to understand whether I could replace the 0 in a binomial distribution from rbinom
with a value of 2, so that it draws from a 2 or a 1 instead of 0 or 1.
Upvotes: 0
Views: 431
Reputation: 25914
To sample from a vector x = c(1,2)
with probabilites c(0.25, 0.75)
you can use
sample.int(2, 1, prob=c(0.25, 0.75))
or
s = rbinom(1, 1, prob = 0.25) # sample zeros or ones
# and convert zeros to two
2 - s
Check that it gives the expected results by drawing more samples
set.seed(76422247)
s = sample.int(2, 1e6, TRUE, prob=c(0.25, 0.75))
proportions(table(s))
# 1 2
# 0.250207 0.749793
set.seed(76422247)
s2 = 2 - rbinom(1e6, 1, prob = 0.25)
proportions(table(s2))
# 1 2
# 0.250207 0.749793
Upvotes: 2