Storing results of loop iterations in R

2020-02-14 02:49发布

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. 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`

3条回答
干净又极端
2楼-- · 2020-02-14 03:42

The easiest way to store model results by iterations is in a list:

List = list()
for(i in 1:100)
    {
       LM = lm(rnorm(10)~rnorm(10))
       List[[length(List)+1]] = LM
     }
查看更多
贼婆χ
3楼-- · 2020-02-14 03:49

I'm pretty sure to save all iterations of the RSS's you could do something like this:

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


      }
     }
    }
查看更多
ら.Afraid
4楼-- · 2020-02-14 03:51

You can probably avoid the for loop altogether. 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="_")]] <- ... 
查看更多
登录 后发表回答