Linear Regression and group by in R

前端 未结 10 1282
抹茶落季
抹茶落季 2020-11-22 02:27

I want to do a linear regression in R using the lm() function. My data is an annual time series with one field for year (22 years) and another for state (50 sta

10条回答
  •  臣服心动
    2020-11-22 02:46

    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 the results or anything else ...
      png(filename = sprintf("diamonds_price=glm(%s).png", strCols[7+i]))
      par(mfrow = c(2, 2))      
      plot(model[[i]])
      dev.off()
      }
    

提交回复
热议问题