【问题标题】:Storing results of loop iterations in R在 R 中存储循环迭代的结果
【发布时间】:2013-10-04 03:45:11
【问题描述】:

我正在尝试存储下面代码的结果,但是我只能想出一个解决方案来保存具有最小残差平方和的模型的结果。这在结果处于 c 和 gamma 范围内之前很有用,因此我需要评估其他点的特征。为此,我需要存储每次迭代的结果。有谁知道在这种情况下该怎么做?

提前致谢!

dlpib1 <- info$dlpib1
scale <- sqrt(var(dlpib1))
RSS.m <- 10

for (c in seq(-0.03,0.05,0.001)){
  for (gamma in seq(1,100,0.2))
    {
    trans <- (1+exp(-(gamma/scale)*(dlpib1-c)))^-1
    grid.regre <-lm(dlpib ~ dlpib1 + dlpib8 + trans + trans*dlpib1 + 
                  + I(trans*dlpib4) ,data=info) 
coef <- grid.regre$coefficients
RSS <- sum(grid.regre$residuals^2)

if (RSS < RSS.m){
  RSS.m <- RSS
  gamma.m <- gamma
  c.m <- c
  coef.m <- coef
  }
 }
}
grid <- c(RSS=RSS.m,gamma=gamma.m,c=c.m,coef.m)
grid`

【问题讨论】:

  • 作为一般提示,避免在R 中使用c 作为变量名,因为它也是使用率最高的函数之一的名称,c( )

标签: r loops iteration storing-information


【解决方案1】:

我很确定会保存 RSS 的所有迭代,您可以这样做:

dlpib1 <- info$dlpib1
    scale <- sqrt(var(dlpib1))
    RSS.m <- rep(0,N)
    coef <- rep(0,N)
    i <- 0

    for (c in seq(-0.03,0.05,0.001)){
      for (gamma in seq(1,100,0.2))
        {
        trans <- (1+exp(-(gamma/scale)*(dlpib1-c)))^-1
        grid.regre <-lm(dlpib ~ dlpib1 + dlpib8 + trans + trans*dlpib1 + 
                      + I(trans*dlpib4) ,data=info) 
    coef <- grid.regre$coefficients
    RSS.m[i] <- sum(grid.regre$residuals^2)
    i=i+1


      }
     }
    }

【讨论】:

    【解决方案2】:

    您可以完全避免for 循环。然而,至于如何完成你的任务,你只需要索引你存储值的任何对象。例如,

    # outside the for loop
    trans <- list()
    
    # inside the for loop
    trans[[paste(gamma, c, sep="_")]] <- ... 
    

    【讨论】:

    • 你好,里卡多。很抱歉这么久才问这个问题,但是我正在编写一个使用此函数的包,当我包含更多参数(如 c.c)时,它需要很长时间才能完成循环。我注意到你说我可以避免循环结果。你能告诉我你认为这是怎么做到的吗?非常感谢!
    • 嗨哈维尔,最好为此打开一个新问题并将银行链接到这个
    【解决方案3】:

    通过迭代存储模型结果的最简单方法是在list

    List = list()
    for(i in 1:100)
        {
           LM = lm(rnorm(10)~rnorm(10))
           List[[length(List)+1]] = LM
         }
    

    【讨论】:

    • 谢谢大家。我选择了 Roxxy.32 的解决方案。这是最终代码
    猜你喜欢
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2021-01-03
    相关资源
    最近更新 更多