[英]How can I perform and store linear regression models between all continuous variables in a data frame?
Let's say I'm using mtcars
in R and I want to perform linear regressions between all possible combinations of numeric variables, and store them (in a list or maybe a different data structure if there's a better one).假设我在 R 中使用
mtcars
,我想在数字变量的所有可能组合之间执行线性回归,并将它们存储(在列表中,或者如果有更好的数据结构,则可能存储在不同的数据结构中)。 How would I accomplish that?我将如何做到这一点? I've seen similar posts like this one , but this approach only runs regressions with col1 against col2, col1 against col3...etc.
我看过类似的帖子,但这种方法只运行 col1 对 col2、col1 对 col3 等的回归。 I want a solution that also runs regressions between col2 and col3 (ie all pairwise comparisons).
我想要一个在 col2 和 col3 之间也运行回归的解决方案(即所有成对比较)。 Any help would be greatly appreciated.
任何帮助将不胜感激。
Assuming you need pairwise comparisons between all columns of mtcars
, you can use combn()
function to find all pairwise comparisons (2), and perform all linear models with:假设您需要在
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
will be your list with all of the linear models together, with both forward and reverse directions of associations between the two variables. all
将是您的列表,其中包含所有线性模型,两个变量之间关联的正向和反向方向。
If you want combinations between three variables, you can do combn(colnames(mtcars), 3)
, and so on.如果你想要三个变量之间的组合,你可以做
combn(colnames(mtcars), 3)
等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.