我想多次从二项式中抽取一个数字。每个绘制对应一个特定的概率(从伯努利以不同的概率绘制)。请避免循环。
y<-c(1:10)
p<- dpois(y,2) #probability vector
#not working below
rbinom(1,1,p) #only return one value
更新:
我使用Jim M的z=vapply(p,function(z){rbinom(1,1,z)},as.integer(1L))
除了Bernoulli部分之外,相同的代码,Matlab是67s但R需要520s。
答案 0 :(得分:4)
这个怎么样?
as.numeric(runif(length(p)) < p)
从均匀分布中取n个随机变量,其中n等于概率分布的长度:length(p)
。将每个值与每个概率进行比较,如果该值小于概率(as.numeric
将TRUE/FALSE
转换为1/0
),则返回1。此外,这比在我的机器上使用vapply快得多:
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))
}
library(microbenchmark)
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
答案 1 :(得分:2)
当p是向量时,结果rbinom
也可以执行类似的任务。它比接受的答案略慢。
rbinom(length(p),size=1,p)
答案 2 :(得分:1)
由于p是概率的向量,我们可以为每个概率生成Bernouilli随机抽取 反过来,依次对每个概率应用相同的函数。使用vapply约束类型返回值,在本例中为整数。
set.seed(12345)
y <- 1:10
p <- dpois(y, 2)
rBernoulli <- vapply(p, function(x) rbinom(1, 1, x), as.integer(1L))