在R中存储循环迭代的结果

时间:2013-09-27 18:25:39

标签: r loops iteration storing-information

我正在尝试存储下面代码的结果,但是我只能想出一个解决方案来保存模型的结果,并使用最小的残差平方和。在结果处于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`

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

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

# outside the for loop
trans <- list()

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

答案 2 :(得分:0)

我非常肯定会保存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


      }
     }
    }