【问题标题】:How can I store rnorm output from a loop in a separate vector?如何将循环的 rnorm 输出存储在单独的向量中?
【发布时间】:2018-05-23 07:54:31
【问题描述】:

我需要将输出存储到一个单独的向量中,以便我可以绘制数据(yearsreproduction_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)
}

【问题讨论】:

    标签: r regex loops random


    【解决方案1】:

    如果你可以放弃打印,

    storage <- rnorm(n=20, mean=1, sd=0.4)+N
    

    会起作用。否则,

    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
    

    【讨论】:

    • 对不起,本,我在看到你回复之前写了这个!我会删除。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2022-07-21
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多