2

I'd like to compact the creation of a vector y . It is the rowsum of some binary binomials with a probability each. With rbinom() I tried to define all probabilities at once but it doesn't give me what I want. Here I show the means, but most important to me are the PDFs.

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
jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • 1
    `size` refers to the "number of trials" in the binomial distribution so changing this from 1 to 3 is sampling from a different distribution. Further, if you don't call `set.seed(8659)` prior to the second attempt of `rbinom` your results will never be replicated. – ruaridhw Feb 05 '18 at 13:16

1 Answers1

1

You can create a vetor with the probabilities and loop over it and take the mean, i.e.

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