简体   繁体   中英

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"

I am a SAS convert so relatively new to R functions and looking for help, Hopefully this is a simple fix. 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

for (i in 2:N)

(note the capital N). I imagine that N is defined as something in your workspace, but not what you want. If you change that to n , does it work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM