循环线性回归和保存系数

时间:2016-01-11 12:41:39

标签: r for-loop linear-regression lapply sapply

这是数据集的一部分(名为" 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-loop,lapply或其他东西。有人能帮我吗?

3 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:3)

broom包在这里也非常有用。

library(dplyr)
library(broom)

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

答案 2 :(得分:1)

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

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