[英]How to correct a simple function: getting error replacement has length zero
I am trying to simulate a branding process with a negative binomial offspring distribution.我正在尝试使用负二项式后代分布来模拟品牌推广过程。 When I run a single branching process, the code works fine.
当我运行单个分支进程时,代码工作正常。 When I wrap it in a function and use the "replicate" function to simulate many branching processes, it produces the error: "replacement has length zero"
当我将它包装在 function 中并使用“复制” function 来模拟许多分支过程时,它会产生错误:“替换长度为零”
I am a SAS convert so relatively new to R functions and looking for help, Hopefully this is a simple fix.我是 SAS 转换所以相对较新的 R 功能并寻求帮助,希望这是一个简单的修复。 and any advice for improvement is always welcome.
并且随时欢迎任何改进建议。 Thank you in advance!
先感谢您!
#######
#Single NB Branching Process with 20 generations
n<-20 #20 generations
r0<-0.9
k<-0.25
#initialize list of population size at generation n
Z<-1
#Initiate with one index case generation 0
Z[0] <- 1
#Cluster size a generation 1
Z[1] <- rnbinom(Z[0], k,r0)
for (i in 2:n)
{
if(Z[i-1]==0) {Z[i]=0} else
{
x<-rnbinom(Z[i-1], k,r0)
Z[i]<- sum(x)
}
}
print(Z)
######################
#Wrap in a function and replicate 300 times
nbbp<-function(n, r0, k)
{
#initialize list of population size at generation n
Z<-1
#Initiate with one index case generation 0
Z[0] <- 1
#Cluster size a generation 1
Z[1] <- rnbinom(Z[0], k,r0)
for (i in 2:N)
{
if(Z[i-1]==0) {Z[i]=0} else
{
x<-rnbinom(Z[i-1], k,r0)
Z[i]<- sum(x)
}
}
}
ds<-replicate(100,nbbp(20,0.9,0.25))
#Returns: Error in Z[1] <- rnbinom(Z[0], k, r0) : replacement has length zero
In your standalone code, you have在您的独立代码中,您有
for (i in 2:n)
while in the function you have而在 function 你有
for (i in 2:N)
(note the capital N). (注意大写 N)。 I imagine that
N
is defined as something in your workspace, but not what you want.我想
N
被定义为您工作区中的某些东西,但不是您想要的。 If you change that to n
, does it work?如果将其更改为
n
,它会起作用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.