Select a specific number with probability

How to choose a number with a certain probability p ?

Say we have to choose between {0, 1} , and probability p means choice 1 .

So, when p=0.8 we choose 1 with 80% and 0 with 20%.

Is there a simple solution to this in R?

+6
source share
1 answer

Take a look at sample .

 > set.seed(1) > sample(c(0,1), size=10, replace=TRUE, prob=c(0.2,0.8)) [1] 1 1 1 0 1 0 0 1 1 1 

From the help file you can read:

sample takes a sample of the specified size from the x elements, using either with or without a replacement.

and the prob argument in sample acts like ...

A vector of probabilistic weights for obtaining elements of a selected vector.

+13
source

All Articles