Linear Regression and group by in R

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

    I think it's worthwhile to add the purrr::map approach to this problem.

    library(tidyverse)
    
    d <- data.frame(state=rep(c('NY', 'CA'), c(10, 10)),
                                     year=rep(1:10, 2),
                                     response=c(rnorm(10), rnorm(10)))
    
    d %>% 
      group_by(state) %>% 
      nest() %>% 
      mutate(model = map(data, ~lm(response ~ year, data = .)))
    

    See @Paul Hiemstra's answer for further ideas on using the broom package with these results.

提交回复
热议问题