locket
locket

Reputation: 761

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

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.

Upvotes: 1

Views: 622

Answers (3)

jblood94
jblood94

Reputation: 16981

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(p) >= p) # for 0 with probability p
#>  [1] 1 1 1 1 0 1 1 1 0 1

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76402

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)

Upvotes: 2

Zheyuan Li
Zheyuan Li

Reputation: 73265

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.

Upvotes: 3

Related Questions