Home > Back-end >  Append results in for loop to a new dataframe in R
Append results in for loop to a new dataframe in R

Time:10-07

I am testing the model fit of multiple different models stored as columns in a single dataframe. I am using a loop to calculate the model fit parameters of each model compared to the actual gaged values (also stored in the df). The model fit is calculating correctly. I would like the results to be appended to a dataframe so that each row of the dataframe contains the model fit parameters. I am doing it by writing it to a list, then converting the list to a dataframe outside of the loop. The list is coming out empty. Any suggestions?

datalist <- list()
for(i in colnames(df)){
  modelPerf <- data.frame(i,
                RMSE = RMSE(as.numeric(df[[paste(i, sep = "")]]),Farad$`MarBASEFarad  ActualActual`),
                R2 = R2(as.numeric(df[[paste(i, sep = "")]]),Farad$`MarBASEFarad  ActualActual`),
                NSE = NSE(as.numeric(df[[paste(i, sep = "")]]),Farad$`MarBASEFarad  ActualActual`),
                pbias = pbias(as.numeric(df[[paste(i, sep = "")]]),Farad$`MarBASEFarad  ActualActual`))
  datalist[[modelPerf]]
}
finaldf <- do.call(rbind,datalist)

CodePudding user response:

The root of your problem is that you need to assign to the list. But also, you're repeating a lot of code, which is inefficient and bug-prone.

Without test data this is untested, but I think this should be work a little more efficiently as well as being much more readable:

datalist <- list()
target <- Farad$`MarBASEFarad  ActualActual`
for(i in colnames(df)){
  fitted <- as.numeric(df[[i]])
  datalist[[i]] <- data.frame(
    model = i,
    RMSE = RMSE(fitted, target),
    R2 = R2(fitted, target),
    NSE = NSE(fitted, target),
    pbias = pbias(fitted, target)
  )
}
finaldf <- do.call(rbind, datalist)
  • Related