Dan*_*lUp 2 for-loop r 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
Run Code Online (Sandbox Code Playgroud)
我想使用线性模型并保存系数如下:
male<-lm(ME1$rateM~exp(AgeR))
summary(male)
coeff <- summary(male)$coefficients[2]
Run Code Online (Sandbox Code Playgroud)
问题是我需要每年(从1751年到2014年)重复此过程,我想将所有系数保存到一个数据集中,如下所示:
Year coeff
1751 0.1556977
1752 0.0966664
...
2014 0.0420914
Run Code Online (Sandbox Code Playgroud)
我不知道我是否必须使用for-loop,lapply或其他东西.有人能帮我吗?
有几种方法可以做到这一点.首先,我们创建一些生成的数据用于说明目的:
set.seed(123)
dat <- expand.grid(year=2000:2010, AgeR=seq(-1,1,0.1))
dat$value <- rnorm(nrow(dat))
Run Code Online (Sandbox Code Playgroud)
我们可以从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
}))
Run Code Online (Sandbox Code Playgroud)
我们可以使用data.table来做同样的事情:
library(data.table)
res2 <- setDT(dat)[,.(coeff=coef(lm(value~exp(AgeR)))[2]),year]
res2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1775 次 |
| 最近记录: |