如何在一个命令中对二进制二项式求和?

How to sum binary binomials in one command?

我想压缩矢量的创建 y。它是一些二进制二项式的行和,每个二项式都有一个概率。使用 rbinom() 我试图一次定义所有概率,但它没有给我想要的东西。我在这里展示方法,但对我来说最重要的是 PDF。

set.seed(8659)
n <- 1e3

a <- rbinom(n, 1, .7)
b <- rbinom(n, 1, .6)
c <- rbinom(n, 1, .05)

df1 <- data.frame(a, b, c, y = a + b + c)
mean(df1$y)
# [1] 1.303

# failed attempt to do this in one command
y <- rbinom(n, 3, c(.7, .6, .05))
mean(y)
# [1] 1.376

您可以创建一个包含概率的向量并对其进行循环并取平均值,即

set.seed(8659)
n <- 1e3
mean(rowSums(sapply(c(.7, .6, .05), function(i) rbinom(n, 1, i))))
#[1] 1.303