【发布时间】:2022-01-14 17:16:16
【问题描述】:
我正在绘制具有多个循环(for 和 while)的模拟结果 - 考虑以下简化的、可重现的示例,该示例绘制了 100 个模拟兔子家庭(每个家庭以一只兔子)以及这个家庭需要多长时间才能灭绝。我想在图中添加一条线,表示来自所有模拟家庭的兔子的中位数和一个表示四分位距的带。
我特别需要帮助来确定循环结构中我可以存储每个模拟家庭的最终家庭规模的位置,这是初始bunnies 和每一代后续bunnies_produced 的总和。
下面我提供了我拥有的当前数字(左)和我想要的数字(右;中位数和 IQR 的组合值)。
我尝试过初始化变量totalbunnies 并在不同的地方添加totalbunnies 或totalbunnies[i],但它从未正确计算每个家庭的总和(请参阅注释掉的行)。
我确实不需要在实际可视化方面需要帮助,我可以添加线条/条带,只需要具体帮助了解每个人的最终家庭规模的存储位置模拟。
# 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)
}
【问题讨论】:
-
totalbunnies应该是矢量还是缩放器?它在您的注释代码中被视为两者。
标签: r loops for-loop while-loop