循环线性回归和节省系数

Loop linear regression and saving coefficients

这是我正在使用的数据集(名为 "ME1")的一部分(所有变量都是数字):

   Year  AgeR   rateM
1  1751 -1.0 0.241104596
2  1751 -0.9 0.036093609
3  1751 -0.8 0.011623734
4  1751 -0.7 0.006670552
5  1751 -0.6 0.006610552
6  1751 -0.5 0.008510828
7  1751 -0.4 0.009344041
8  1751 -0.3 0.011729740
9  1751 -0.2 0.010988005
10 1751 -0.1 0.015896107
11 1751  0.0 0.018190140
12 1751  0.1 0.024588340
13 1751  0.2 0.029801362
14 1751  0.3 0.044515912
15 1751  0.4 0.055240354
16 1751  0.5 0.088476758
17 1751  0.6 0.119045309
18 1751  0.7 0.167866571
19 1751  0.8 0.239244825
20 1751  0.9 0.329683010
21 1751  1.0 0.472448318

我想使用线性模型并按如下方式保存系数:

male<-lm(ME1$rateM~exp(AgeR))
summary(male)
coeff <- summary(male)$coefficients[2]

问题是我需要每年(从 1751 年到 2014 年)重复此过程,并且我想将所有系数保存到一个数据集中,如下所示:

Year coeff
1751 0.1556977
1752 0.0966664
...
2014 0.0420914

我不知道我是否必须使用 for 循环、lapply 或其他东西。有人能帮我吗?

有几种方法可以做到这一点。首先,我们创建一些生成的数据用于说明目的:

set.seed(123)
dat <- expand.grid(year=2000:2010, AgeR=seq(-1,1,0.1))
dat$value <- rnorm(nrow(dat))

我们可以从 base-R 开始。我们按年份拆分数据,拟合模型并提取系数。然后我们将所有东西绑定在一起。

res <- do.call(rbind,lapply(split(dat, dat$year),function(x){
  fit <- lm(value~exp(AgeR), data=x)
  res <- data.frame(year=unique(x$year),coeff=coef(fit)[2])
  res
}))

我们可以使用 data.table 做同样的事情:

library(data.table)


res2 <- setDT(dat)[,.(coeff=coef(lm(value~exp(AgeR)))[2]),year]
res2

broom 包在这里也很有用。

library(dplyr)
library(broom)

mtcars %>%
  group_by(gear) %>%
  do(tidy(lm(mpg ~ am + cyl, data = .)))

nlme 包为此提供了一个方便的功能:

library(nlme)
coef(lmList(value ~ exp(AgeR)| year, data=dat))[,2, drop = FALSE]