Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Randomly generating binomial values of 1 and 2 using rbinom in R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To sample from a vector x = c(1,2) with probability c(0.75, 0.25) 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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading