Linear Regression and group by in R

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

    Here's an approach using the plyr package:

    d <- data.frame(
      state = rep(c('NY', 'CA'), 10),
      year = rep(1:10, 2),
      response= rnorm(20)
    )
    
    library(plyr)
    # Break up d by state, then fit the specified model to each piece and
    # return a list
    models <- dlply(d, "state", function(df) 
      lm(response ~ year, data = df))
    
    # Apply coef to each model and return a data frame
    ldply(models, coef)
    
    # Print the summary of each model
    l_ply(models, summary, .print = TRUE)
    

提交回复
热议问题