Phaml Phaml - 1 year ago 94
R Question

draw from binomial with changing probability

I want to draw only one number from binomial many times. Each draw corresponding to a specific probability (draw from Bernoulli with different probability). Please avoid loop.

p<- dpois(y,2) #probability vector

#not working below

rbinom(1,1,p) #only return one value

I used Jim M's
The same codes except for the Bernoulli part, Matlab is 67s but R takes 520s.

Answer Source

How about this?

as.numeric(runif(length(p)) < p)

Take n random variables from uniform distribution where n is equal to the length of probability distribution: length(p). Compare each value with each probability and return 1 if the value is smaller than the probability ( as.numeric converts TRUE/FALSE to 1/0). Also, this is a lot faster than using vapply on my machine:

y <- 1:1000
p <- dpois(y, 2)

rBernoulli <- function(p){
    vapply(p, function(x) rbinom(1, 1, x), as.integer(1L))

rBernoulli2 <- function(p){
    var(as.numeric(runif(length(p)) < p))

microbenchmark(rBernoulli(p), rBernoulli2(p))
## Unit: microseconds
##            expr      min       lq      mean    median       uq      max neval
##   rBernoulli(p) 2110.307 2197.771 2699.7286 2245.7425 2413.532 6966.376   100
##  rBernoulli2(p)   66.045   70.062   91.8782   93.9355  103.083  186.086   100
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download