存储 while 循环中产生的值的总和

Storing sum of values produced in a while-loop

我正在绘制具有多个循环(forwhile)的模拟结果 - 请考虑以下简化的、可重现的示例,该示例绘制了 100 只模拟兔子在一个家庭中生产的兔子数量家庭(每个家庭从一只兔子开始)以及这个家庭灭绝需要多长时间。我想在图中添加一条线,代表来自所有模拟家庭的兔子的中位数和代表四分位间距的带。

我特别需要帮助来确定循环结构中我可以存储每个模拟家庭的最终家庭规模的位置,这是每个模拟家庭的初始 bunnies 和所有后续 bunnies_produced 的总和世代.

下面我提供了我现有的数字(左)和我想要的数字(右;由中位数和 IQR 组成的值)。

我尝试启动一个变量 totalbunnies 并在不同的地方添加 totalbunniestotalbunnies[i],但它从未正确计算每个家庭的总和(请参阅注释掉的行)。

不需要实际可视化方面的帮助,我可以在lines/bands中添加,只需要具体帮助关于在何处存储每个模拟的最终家庭大小。

# Initiate plot
plot(NA, xlim = c(0, 10), ylim = c(0, 25), 
     xlab="Duration", ylab = "Number of Bunnies", frame = FALSE)

totalbunnies <- c() # initiate to store total number of bunnies in each sim

# Run simulations
set.seed(0506)
for(i in 1:100) {
  bunnies <- 1 
  t <- rep(0, 1) 
  duration <- t 
  while(bunnies > 0) {
    bunnies_produced <- rnbinom(bunnies, mu = 0.5, size = 0.25) 
    t.new <- numeric()
    for(j in 1:length(bunnies_produced)) {
      t.new <- c(t.new, t[j] + rgamma(bunnies_produced[j], shape = 0.25, rate = 0.5))
      #totalbunnies <- sum(totalbunnies, bunnies_produced)
    }
    bunnies <- length(t.new) 
    t <- t.new
    duration <- c(duration, t.new)
    # totalbunnies[i] <- sum(bunnies, bunnies_produced)
    # totalbunnies <- sum(totalbunnies, bunnies_produced)
  } 
  #totalbunnies[I] <- max(duration)
  lines(sort(duration), 1:length(duration), col = "maroon", lwd = 1) 
  points(max(duration), length(duration), col = "maroon", pch = 16)
}

通过在 lines() 参数

之前添加 totalbunnies[i] <- length(duration) 而不是 max(duration) 来找到兔子总数的总和