Search code examples
rloopslinear-regressionexport-to-excel

Print and export loop from simple linear regression


I did a loop to perform a numerous simple linear regression in a dataset. But then, I only want to print the result that meet the certain threshold (ie: R-squared > 30% and p-value < 5%). Then I also want to save and export the list into csv file. But then, it only save the first result from the loop. Not all the list, while actually there were about 14 of them that meet the threshold. Is there something wrong with my code?

predictorlist = colnames(finalmev)[-1]
sink('mev.txt')
for (i in predictorlist){ 
  model <- summary(lm(paste("ODR ~", i[[1]]), data=finalmev))
  if (model$r.squared > 0.30 && model$coefficients[2,4] < 0.05){
    print(data.frame(MEV = i[[1]], Rsquared = model$r.squared,
                     pvalue = model$coefficients[2,4]))
    sink()
  }
}

Solution

  • Using lapply, taking mtcars as an example -

    predictorlist = colnames(mtcars)[-1]
    
    do.call(rbind, lapply(predictorlist, function(x) {
      model <- summary(lm(paste("mpg ~", x), data=mtcars))
      rsq = model$r.squared
      pval = model$coefficients[2,4]
      if (rsq > 0.30 && pval < 0.05) 
         data.frame(MEV = x, Rsquared = rsq, pvalue = pval)
    })) -> res
    
    
    write.csv(res, 'mev.csv', row.names = FALSE)
    #If you want to write it as text file
    #write.table(res, 'mev.txt')