Hi Carrie,

Use the first approach:

n <- 5
p <- c(0.2, 0.9, 0.15, 0.8, 0.75)
rbinom(n, 1, p)
# [1] 0 0 0 1 1
rbinom(n, 1, p)
# [1] 1 1 0 1 1

To check, replicate the analysis 5000 times and then estimate the
probability for each subject:

rowMeans(replicate(5000, rbinom(n, 1, p)))
# 0.2002 0.9026 0.1550 0.8020 0.7562

Using Erik's solution you will get the "same" results:

> rowMeans(replicate(5000, sapply(p, function(x) sample(0:1, 1, prob =
c(1-x, x)))))
# [1] 0.1958 0.9006 0.1492 0.8066 0.7446

Note that in both cases the result is close to the original values of p.

HTH,
Jorge


On Sat, May 22, 2010 at 10:52 PM, 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 ?
>
> suppose there are 5 subjects, and their probabilities of this Bernoulli
> variable is  p=c(0.2, 0.9, 0.15, 0.8, 0.75)
> n<-5
> Ber.var <- rbimon(n,1,p) ## I doubt if this will take the first
> probability,
> which is 0.2, but won't change for each subject ??
>
> ## or should I use
> Ber.var <- sample(c(0,1), n, prob=p, replace=TRUE)
>
> Or any suggestions on how I can check if the probability of drawing this
> binary variable is based on the subject's probabilities ?
>
> Thanks for help!!
>
> Carrie
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to