首页 > 解决方案 > 从多个线性模型中获取斜率、截距和确定系数,所有这些都来自同一个数据帧

问题描述

我有以下数据框:

Index <- seq.int(1:10)
A <- c(5, 5, 3, 4, 3, 3, 2, 2, 4, 3)
B <- c(10, 11, 12, 12, 12, 11, 13, 13, 14, 13)
C <- c(7, 6, 7, 7, 6, 5, 6, 5, 5, 4)
df <- data.frame(Index, A, B, C)
> df
      Index A  B C
 [1,]     1 5 10 7
 [2,]     2 5 11 6
 [3,]     3 3 12 7
 [4,]     4 4 12 7
 [5,]     5 3 12 6
 [6,]     6 3 11 5
 [7,]     7 2 13 6
 [8,]     8 2 13 5
 [9,]     9 4 14 5
[10,]    10 3 13 4

我想生成线性模型(并最终以易于使用的数据框形式获得斜率、截距和确定系数),将Index列作为因变量,将所有其他列作为响应变量,分别地。我知道我可以通过运行以下代码行来做到这一点:

summary(lm(cbind(A, B, C) ~ Index, data = df))

我对上述代码行的一个问题是它使用了该cbind函数,因此我必须分别输入每一列。我正在处理一个包含许多列的大型数据框,而不是使用该cbind函数,我希望能够通过编写类似df[, 2:ncol(df)]的东西来告诉该函数一次使​​用一堆列(即响应变量) cbind(A, B, C).

我对上述代码行的另一个问题是输出并不是真正用户友好的形式。最终,我希望输出(斜率、截距和确定系数)采用易于使用的数据框形式:

response <- c("A", "B", "C")
slope <- c(-0.21818, 0.33333, -0.29091)
intercept <- c(4.60000, 10.26667, 7.40000)
r.squared <- c(0.3776, 0.7106, 0.7273)
summary_df <- data.frame(response, slope, intercept, r.squared)
> summary_df
  response    slope intercept r.squared
1        A -0.21818   4.60000    0.3776
2        B  0.33333  10.26667    0.7106
3        C -0.29091   7.40000    0.7273

最有效的方法是什么?必须有一个使用lapply我没有得到的功能的解决方案。非常感谢!

标签: r

解决方案


要解决查询的第一部分,您可以将matrix对象传递到lm公式侧:

summary(lm(as.matrix(df[-1]) ~ as.matrix(df[1])))

根据报告的系数检查:

all.equal(
  coef(lm(as.matrix(df[-1]) ~ as.matrix(df[1]))),
  coef(lm(cbind(A,B,C) ~ Index, data=df)),
  check.attributes=FALSE
)
#[1] TRUE

请注意李哲源的警告,即组合这种方式不会matrix(...) ~ .按预期工作。通常将两边都指定为表达式或仅将两边指定为矩阵可能更安全。


推荐阅读