首页 > 解决方案 > 按年循环 lm

问题描述

我在 R 中有一个数据框,看起来像上面

Id  ln_W  Year  Exp 
1   2.5   2010   15
1   2.3   2011   16
2   2.1   2010   20
3   2.5   2012   17
3   2.5   2013   18

我想在我的数据集中每年对 ln_W~Exp 进行回归,并将结果摘要保存为列表格式。

有谁知道如何做到这一点?

标签: rgroup-bylm

解决方案


base R中,我们split通过Year, 循环listwith lapply,创建模型lm并将输出存储为list

out <- lapply(split(df1, df1$Year), function(x)
                   lm(ln_W ~ Exp, data = x))

注意:这不需要任何软件包


或者另一个选项lmList来自lme4

library(lme4)
lmList(ln_W  ~Exp | Year, data = df1)
#Call: lmList(formula = ln_W ~ Exp | Year, data = df1) 
#Coefficients:
#     (Intercept)   Exp
#2010         3.7 -0.08
#2011         2.3    NA
#2012         2.5    NA
#2013         2.5    NA

#Degrees of freedom: 5 total; -3 residual
#Residual standard error: 0

数据

df1 <- structure(list(Id = c(1L, 1L, 2L, 3L, 3L), ln_W = c(2.5, 2.3, 
2.1, 2.5, 2.5), Year = c(2010L, 2011L, 2010L, 2012L, 2013L), 
    Exp = c(15L, 16L, 20L, 17L, 18L)), class = "data.frame",
    row.names = c(NA, 
-5L))

推荐阅读