要从具有上限/下限的泊松分布中抽取的样本编号

问题描述 投票:0回答:1

[在R中工作,我需要创建一个长度为n的向量,其值是从带有Lambda = 1的泊松分布中随机抽取的值,但其下限为2,上限为6(即所有数字将是2、3、4、5或6)。

我不确定如何执行此操作。我尝试创建一个for循环,用该范围内的值替换该范围外的任何值:

seed(123)
n<-25 #example length
example<-rpois(n,1)
test<-example #redundant - only duplicating to compare with original *example* values
 for (i in 1:length(n)){
   if (test[i]<2||test[i]>6){
     test[i]<-rpois(1,1)
   }
 }

但是这似乎不起作用(在test中仍然得到0和1,依此类推)。任何想法将不胜感激!

r poisson
1个回答
0
投票

这是一种生成具有泊松分布的n数并将范围外的所有数字替换为范围内的随机数的方法。

n<-25 #example length
example<-rpois(n,1)
inds <- example < 2 | example > 6
example[inds] <- sample(2:6, sum(inds), replace = TRUE)
© www.soinside.com 2019 - 2024. All rights reserved.