通过 R 中线性回归中预测变量的两种组合

By two combinations of predictors in linear regression in R

假设我有 X1,...,X14 个潜在的预测因子。

现在对于给定的 Y 我想制定 OLS 方案:

Y~X1+X2
Y~X1+X3
 ....
Y~X1+X14
....
Y~X14+X13

这基本上是所有预测变量的两个组合。创建所有这些回归后,我想在 predict 函数中使用它们(如果可能)。

我的问题是:如何通过两个回归变量的组合来进行所有这些回归?

您可以对所有组合使用 combn,然后使用 apply 创建所有公式:

#all the combinations
all_comb <- combn(letters, 2)

#create the formulas from the combinations above and paste
text_form <- apply(all_comb, 2, function(x) paste('Y ~', paste0(x, collapse = '+')))

输出

> text_form
  [1] "Y ~ a+b" "Y ~ a+c" "Y ~ a+d" "Y ~ a+e" "Y ~ a+f" "Y ~ a+g".....

然后您可以使用 as.formula 将上述公式输入到回归中,将文本转换为公式(很可能在另一个 apply 中)。

您也可以像这样将它们放入一行公式中:

mySpecs <- combn(letters[1:3], 2, FUN=function(x) reformulate(x, "Y"),
                 simplify=FALSE)

哪个 returns 列表可用于 lapply 到 运行 回归:

mySpecs
[[1]]
Y ~ a + b
<environment: 0x4474ca0>

[[2]]
Y ~ a + c
<environment: 0x4477e68>

[[3]]
Y ~ b + c
<environment: 0x447ae38>

然后您将执行以下操作以获得回归结果列表。

myRegs <- lapply(mySpecs, function(i) lm(i, data=df))