admin管理员组

文章数量:1122846

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.

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.

Share Improve this question asked Nov 21, 2024 at 23:49 AsiganAsigan 1054 bronze badges 3
  • 1 rpois(8, c(2,2,2,2,2, 3,3,3)) would do it. There are many other ways to generate the vector of means, but for this length you may as well just write it out. – user2554330 Commented Nov 22, 2024 at 0:28
  • @user2554330 Thanks for your comment! May I wonder whether this syntax follows from some general rule of R? I did not see that way of using rpois on the document of the function stat.ethz.ch/R-manual/R-devel/library/stats/html/Poisson.html . – Asigan Commented Nov 22, 2024 at 1:51
  • @Asigan: yes, lots of R functions accept vectors for parameters and apply them successively to the vector result. ?rpois says lambda (the mean) is a "vector of (non-negative) means". – user2554330 Commented Nov 22, 2024 at 10:32
Add a comment  | 

1 Answer 1

Reset to default 3

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.

本文标签: Use R to generate a sequence random numbers of Poisson distribution with different meanStack Overflow