Home > OS >  R sampling either 0 and 1 based on a vector of probabilities
R sampling either 0 and 1 based on a vector of probabilities

Time:07-27

I want to sample 10 numbers, either 0 or 1, with the following chances:

c(0.1989185, 0.2879522, 0.1142932, 0.3057067, 0.2056559, 0.1492126, 
0.2775737, 0.3332775, 0.9276861, 0.4373286)

The first number has a 0.1989185 chance of being 0, and the second has a 0.2879522 chance of being 0, etc.

CodePudding user response:

Let x be your vector of probability, we can use:

rbinom(length(x), 1, prob = 1 - x)

Note: it is not prob = x, because your probability is for getting 0, not 1.

CodePudding user response:

Compare your probability vector to a random uniform of the same length.

set.seed(94)
p <- c(0.1989185,0.2879522,0.1142932,0.3057067,0.2056559,0.1492126,0.2775737,0.3332775,0.9276861,0.4373286)
 (runif(length(p)) >= p) # for 0 with probability p
#>  [1] 1 1 1 1 0 1 1 1 0 1

CodePudding user response:

This is just

p <- scan(text="0.1989185 0.2879522 0.1142932 0.3057067 0.2056559 0.1492126 0.2775737 0.3332775 0.9276861 0.4373286")
rbinom(length(p), 1, prob = 1 - p)
#>  [1] 1 1 1 1 1 1 1 1 0 1

Created on 2022-07-26 by the reprex package (v2.0.1)


Simulation with 1 million runs.

r <- replicate(1e6, rbinom(length(p), 1, prob = 1 - p))
plot(p, pch = 16)
points(1:10, rowMeans(1 - r), pch = 4, col = "red")

Created on 2022-07-26 by the reprex package (v2.0.1)

  • Related