How to Loop/Repeat a Linear Regression in R

后端 未结 3 717
自闭症患者
自闭症患者 2020-12-07 21:47

I have figured out how to make a table in R with 4 variables, which I am using for multiple linear regressions. The dependent variable (Lung) for each regression is taken f

3条回答
  •  借酒劲吻你
    2020-12-07 22:05

    The question seems to be about how to call regression functions with formulas which are modified inside a loop.

    Here is how you can do it in (using diamonds dataset):

    attach(ggplot2::diamonds)
    strCols = names(ggplot2::diamonds)
    
    formula <- list(); model <- list()
    for (i in 1:1) {
      formula[[i]] = paste0(strCols[7], " ~ ", strCols[7+i])
      model[[i]] = glm(formula[[i]]) 
    
      #then you can plot or do anything else with the result ...
      png(filename = sprintf("diamonds_price=glm(%s).png", strCols[7+i]))
      par(mfrow = c(2, 2))      
      plot(model[[i]])
      dev.off()
      }
    

提交回复
热议问题