[R] Bernoulli random variable with different probability

Erik Iverson eriki at ccbr.umn.edu
Sun May 23 05:06:01 CEST 2010


Carrie Li wrote:
> Dear R-helpers,
> 
> I would like to generate a variable that takes 0 or 1, and each subject has
> different probabilities of taking the draw.
> 
> So, which of the following code I should use ?
> 
<snip>

I don't think either.

Try this:

probs <- seq(0,1, by = .1)
sapply(probs, function(x) sample(0:1, 1, prob = c(1-x, x)))

probs will be the vector of your probabilities for obtaining a '1' per subject, 
so set that to whatever you want, then run the second line.



More information about the R-help mailing list