-1

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?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
tomka
  • 2,516
  • 7
  • 31
  • 45

1 Answers1

2

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.

Roland
  • 127,288
  • 10
  • 191
  • 288