gpt4 book ai didi

从 R 中的数据帧运行多个简单的线性回归

转载 作者:行者123 更新时间:2023-12-04 14:01:40 25 4
gpt4 key购买 nike

我有一个数据集(数据框),其中 5 列都包含数值。

我希望为数据集中的每一对运行一个简单的线性回归。

例如,如果列被命名为 A, B, C, D, E ,我要跑 lm(A~B), lm(A~C), lm(A~D), ...., lm(D~E) ,... 然后我想绘制每对的数据以及回归线。

我对 R 还很陌生,所以我正在考虑如何实际实现这一点。我应该使用 ddply ?或 lapply ?我不确定如何解决这个问题。

最佳答案

这是使用 combn 的一种解决方案

 combn(names(DF), 2, function(x){lm(DF[, x])}, simplify = FALSE)

例子:
set.seed(1)
DF <- data.frame(A=rnorm(50, 100, 3),
B=rnorm(50, 100, 3),
C=rnorm(50, 100, 3),
D=rnorm(50, 100, 3),
E=rnorm(50, 100, 3))

更新:添加@Henrik 建议(见评论)
# only the coefficients
> results <- combn(names(DF), 2, function(x){coefficients(lm(DF[, x]))}, simplify = FALSE)
> vars <- combn(names(DF), 2)
> names(results) <- vars[1 , ] # adding names to identify variables in the reggression
> results
$A
(Intercept) B
103.66739418 -0.03354243

$A
(Intercept) C
97.88341555 0.02429041

$A
(Intercept) D
122.7606103 -0.2240759

$A
(Intercept) E
99.26387487 0.01038445

$B
(Intercept) C
99.971253525 0.003824755

$B
(Intercept) D
102.65399702 -0.02296721

$B
(Intercept) E
96.83042199 0.03524868

$C
(Intercept) D
80.1872211 0.1931079

$C
(Intercept) E
89.0503893 0.1050202

$D
(Intercept) E
107.84384655 -0.07620397

关于从 R 中的数据帧运行多个简单的线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18947563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com