[英]How to perform linear regression between one column and all other columns in a data frame and save r squared values in new data frame?
[英]How can I perform and store linear regression models between all continuous variables in a data frame?
假设我在 R 中使用mtcars
,我想在数字变量的所有可能组合之间执行线性回归,并将它们存储(在列表中,或者如果有更好的数据结构,则可能存储在不同的数据结构中)。 我将如何做到这一点? 我看过类似的帖子,但这种方法只运行 col1 对 col2、col1 对 col3 等的回归。 我想要一个在 col2 和 col3 之间也运行回归的解决方案(即所有成对比较)。 任何帮助将不胜感激。
假设您需要在mtcars
的所有列之间进行成对比较,您可以使用combn()
function 查找所有成对比较 (2),并执行所有线性模型:
combinations <- combn(colnames(mtcars), 2)
forward <- list()
reverse <- list()
for(i in 1:ncol(combinations)){
forward[[i]] <- lm(formula(paste0(combinations[,i][1], "~", combinations[,i][2])), data = mtcars)
reverse[[i]] <- lm(formula(paste0(combinations[,i][2], "~", combinations[,i][1])), data = mtcars)
}
all <- c(forward, reverse)
all
将是您的列表,其中包含所有线性模型,两个变量之间关联的正向和反向方向。
如果你想要三个变量之间的组合,你可以做combn(colnames(mtcars), 3)
等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.