Linear Regression and group by in R

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

    A nice solution using data.table was posted here in CrossValidated by @Zach. I'd just add that it is possible to obtain iteratively also the regression coefficient r^2:

    ## make fake data
        library(data.table)
        set.seed(1)
        dat <- data.table(x=runif(100), y=runif(100), grp=rep(1:2,50))
    
    ##calculate the regression coefficient r^2
        dat[,summary(lm(y~x))$r.squared,by=grp]
           grp         V1
        1:   1 0.01465726
        2:   2 0.02256595
    

    as well as all the other output from summary(lm):

    dat[,list(r2=summary(lm(y~x))$r.squared , f=summary(lm(y~x))$fstatistic[1] ),by=grp]
       grp         r2        f
    1:   1 0.01465726 0.714014
    2:   2 0.02256595 1.108173
    

提交回复
热议问题