r - 按年循环 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 进行回归,并将结果摘要保存为列表格式。
有谁知道如何做到这一点?
解决方案
在base R
中,我们split
通过Year
, 循环list
with 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))
推荐阅读
- jsx - StencilJS JSX 使用 ref in 作为 Prop
- laravel - 从 Laravel ResourceCollection 从 vue/cli 中读取数据
- mysql - 将 Count 与 Count Distinct 和 Group By 结合使用
- javascript - 有没有办法在javascript中将子数组和子子数组合并为一个?
- xquery - 我们如何在 MarkLogic 中获取文档的本地路径
- laravel-6 - 如何在laravel6中根据对象的特定键值匹配合并集合?
- jenkins - 使用 Helm 和 Jenkins 为基于微服务的应用程序部署 Kubernetes
- git - 如何限制远程 git repo 中的交互?
- haskell - 为什么 Haskell 的括号函数在可执行文件中工作但在测试中无法清理?
- c++ - 如何将不同多个数组中的值传递给新的单个数组?