tomka tomka - 3 months ago 9
R Question

What is the optimal way to draw repeatedly from (0,1) with a vector of varying probabilities? (R)

I often face the problem that I want to draw samples repeatedly with replacement from

c(0,1)
with varying vector of 'success' probabilities
prob
, such as

prob <- c(1:5/10)


Two options using both a
for
loop are:

A <- numeric()
n <- length(prob)
for(i in 1:n){
A[i] <- rbinom( 1 , 1 , prob = prob[i] )
}


and

for(i in 1:n){
A[i] <- sample( c(0,1) , 1 , prob = c(1-prob[i],prob[i]) )
}


Are there more straight forward (optimal, ellegant) ways to do this, e.g. without using the
for
loop?

Answer

All the distribution functions are fully vectorized, e.g.:

set.seed(42)
rbinom(2, 1, c(0.01, 0.99))
#[1] 0 1

rnorm(2, mean = c(1, 1e3))
#[1]    0.4353018 1000.3631284

rf(2, c(1, 10), c(10, 1))
#[1] 1.408771 4.677464

etc.