简体   繁体   English

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

[英]Storing results of loop iterations in R

I am trying to store the results of the the code below, however I could only come up with a solution to save the results of the model with the smallest sum of squared residuals. 我正在尝试存储以下代码的结果,但是我只能想出一种解决方案,以最小的残差平方和保存模型的结果。 This was useful until the results were in the limits of the range of both c and gamma, therefore I need to assess the characteristics of other points. 这是有用的,直到结果在c和γ的范围内为止,因此我需要评估其他点的特征。 For this I need to store the results of every iteration. 为此,我需要存储每次迭代的结果。 Does anyone know how to do this in this case? 有谁知道在这种情况下该怎么做?

Thanks in advance! 提前致谢!

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`

The easiest way to store model results by iterations is in a list : 通过迭代存储模型结果的最简单方法是在list

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

You can probably avoid the for loop altogether. 您可能可以完全避免for循环。 However, as for how to accomplish your task, you simply need to index whatever object you are storing the value in. For example, 但是,关于如何完成任务,您只需索引要在其中存储值的任何对象。例如,

# outside the for loop
trans <- list()

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

I'm pretty sure to save all iterations of the RSS's you could do something like this: 我非常确定要保存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


      }
     }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM