Linear Regression and group by in R

前端 未结 10 1501
抹茶落季
抹茶落季 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:51

    I now my answer comes a bit late, but I was looking for a similar functionality. It would seem the built-in function 'by' in R can also do the grouping easily:

    ?by contains the following example, which fits per group and extracts the coefficients with sapply:

    require(stats)
    ## now suppose we want to extract the coefficients by group 
    tmp <- with(warpbreaks,
                by(warpbreaks, tension,
                   function(x) lm(breaks ~ wool, data = x)))
    sapply(tmp, coef)
    

提交回复
热议问题