rrandom

Use R to generate a sequence random numbers of Poisson distribution with different mean


In R, how to use rpois generate, for instance, 5 random numbers from a Poisson distribution with mean 2, and then 3 random numbers from a Poisson distribution with mean 3, and put them in one vector of length 8?

I have tried

rpois(c(5,3),c(2,3))

but this generates a vector with length 2.


Solution

  • There are lots of ways to do this. The most transparent one might be

    rpt_vec <- c(5,3)
    lambda_vec <- c(2,3)
    rpois(sum(rpt_vec), lambda = rep(lambda_vec, rpt_vec))
    

    sum(rpt_vec) is the total number of deviates you want; rep(...) generates the right number of copies of each lambda_vec value.