【发布时间】:2025-12-21 17:40:11
【问题描述】:
我有一个大约 200 列的数据框,它看起来像这样:
d1 <- structure(list(Date=c(2012, 2012, 2013, 2013, 2014, 2014),
x1=c(NA, NA, 17L, 29L, 27L, 10L), x2=c(30L, 19L, 22L, 20L, 11L,
24L), x3=c(NA, 23L, 22L, 27L, 21L, 26L), x4=c(30L, 28L, 23L,
24L, 10L, 17L), x5=c(12L, 18L, 17L, 16L, 30L, 26L)),
row.names=c(NA, 6L), class="data.frame")
输出:
Date x1 x2 x3 x4 x5
1 2012 NA 30 NA 30 12
2 2012 NA 19 23 28 18
3 2013 17 22 22 23 17
4 2013 29 20 27 24 16
5 2014 27 11 21 10 30
6 2014 10 24 26 17 26
我现在想分别对每一年进行线性回归,并创建一个新的数据框,只使用每年每个变量 x1 到 x4 的截距。我的自变量是 x5。
像这样:
Time x1 x2 x3 x4
1 2012 Interceptx1 Interceptx2 Interceptx3 Interceptx4
2 2013 Interceptx1 Interceptx2 Interceptx3 Interceptx4
3 2014 Interceptx1 Interceptx2 Interceptx3 Interceptx4
我试过lms <- lapply(2:5, function(x) lm(d1[,x] ~ d1$x5)) 和df <- data.frame(sapply(lms, coef))
但这会在整个时间段内运行回归。我的数据框包含 200 列,因此我正在寻找一种有效的方法来创建这个新的数据框。
非常感谢!
【问题讨论】:
-
你能定义你所说的拦截吗?你的意思是来自
lm()的输出吗?另外,您还想使用哪些变量组合来训练模型? -
如果您按年份运行线性回归,并且您希望因变量是
xn列,那么自变量是什么?例如lm(x1 ~ ?, data = d1) -
我编辑了我的帖子。 @Rohit拦截是指我从
df <- data.frame(sapply(lms, coef))获得的拦截。 -
@r.bot 我的自变量是 x5。因此,在我的示例中,按年份进行的回归将是:
lm(x1 ~ x5, data = d1)、lm(x2 ~ x5, data = d1)、lm(x3 ~ x5, data = d1)、lm(x4 ~ x5, data = d1) -
有一个叫做 broom 的包可以做到这一点。
标签: r dataframe regression lapply