我需要将输出存储到单独的向量中,以便我可以绘制数据(years
对reproduction_rate
)。目前它只存储最后一年而不是1:20年。有没有办法使用grep / regex将输出值存储到一个外部向量中,而不是从控制台复制和粘贴?
N <- 1000
years <- 1:20
storage <- ()
for (year in years) {
reproduction_rate <- rnorm(n=1, mean=1, sd=0.4)+N
phrase <- paste("In year", year, "the population rate was", reproduction_rate)
print(paste("In year", year, "the population rate was", reproduction_rate))
storage <- (reproduction_rate)
}
答案 0 :(得分:1)
如果你可以放弃打印,
storage <- numeric(length(years))
for (i in seq_along(years)) {
storage[i] <- rnorm(...)
print("stuff",years[i],...)
}
会奏效。否则,
N <- 1000
nyear <- 20
years <- 1:nyear
set.seed(101)
storage1 <- rnorm(n=nyear, mean=1, sd=0.4)+N
for (i in seq_along(years)) {
print(paste("year",years[i],": reproduction=",storage1[i]))
}
只要你适当地设置了种子,并且在调用随机数生成器之间不运行任何其他命令,无论你是一次选择一个随机数还是一个,你都可以得到完全相同的答案一次。 一下子:
set.seed(101)
storage2 <- numeric(nyear)
for (i in seq_along(years)) {
storage2[i] <- rnorm(1,mean=1,sd=0.4)+N
print(paste("year",years[i],": reproduction=",storage2[i]))
}
一次一个:
all.equal(storage1,storage2) ## TRUE
比较
{{1}}