bernoulli trials with different probabilities

Viewed 426

I am trying to do something like this (just for illustration, I do know why it doesn't work).

sample(c(TRUE, FALSE), 3, prob=c(0.1,0.2,1), replace=TRUE)

I do have weights with which I want the 3 elements drawn. So element 1 should have a success probability of 0.1, element 2 probability 0.2 and element 3 probability 1. In essence, I am performing a series of Bernoulli trials with different success probabilities.

I think there has to be a simple workaround or another option I am not seeing, bc the only thing that comes to my mind is looping

Looping would be slow as I have at least 5000 if not more cases to go through.

Many thanks for any input.

2 Answers

rbinom(n = 3, size = 1, prob = c(.10, .25, .5)) would give you exactly what you are asking for, but with an output of 0/1. If you want it to be a TRUE/FALSE vector you would call: as.logical(rbinom(n = 3, size = 1000, prob = c(.10, .25, .5)))

length(prob) needs to be equal to n, or you will get inconsistent output.

I do have weights with which I want the 3 elements drawn. So element 1 should have a success probability of 0.1, element 2 probability 0.2 and element 3 probability 1. In essence, I am performing a series of Bernoulli trials with different success probabilities.

The rbinom function is vectorized so you can do something this to make 100000 samples from such a three dimensional distribution

sample_func <- function(n)
  matrix(rbinom(n * 3L, 1L, c(.1, .2, 1)), nrow = 3L)

# show an example
set.seed(1)
samples <- sample_func(100000L)

# the means are as expected
rowMeans(samples)
#R> [1] 0.1 0.2 1.0

# show the first five samples
samples[, 1:5]
#R>      [,1] [,2] [,3] [,4] [,5]
#R> [1,]    0    0    0    1    0
#R> [2,]    0    1    1    0    0
#R> [3,]    1    1    1    1    1

A more generic sample function would be

sample_func <- function(n, prob){
  n_ele <- length(prob)
  matrix(rbinom(n * n_ele, 1L, prob), nrow = n_ele)
}

# sample from four dimensional distribution
set.seed(1)
sample_func(5L, c(.1, .2, .4, .8))
#R>      [,1] [,2] [,3] [,4] [,5]
#R> [1,]    0    0    0    0    0
#R> [2,]    0    1    0    0    1
#R> [3,]    0    1    0    1    0
#R> [4,]    0    1    1    1    1
Related