[英]By two combinations of predictors in linear regression in R
Suppose that I have X1,...,X14
potential predictors. 假设我有
X1,...,X14
潜在预测变量。
Now for a given Y
i want to make the OLS scheme: 现在,对于给定的
Y
我想制定OLS方案:
Y~X1+X2
Y~X1+X3
....
Y~X1+X14
....
Y~X14+X13
which is basically all the by two combinations of all the predictors. 这基本上是所有预测变量的两个组合。 After all those regressions are created I want to use them in the
predict
function (if possible). 创建所有这些回归之后,我想在
predict
函数中使用它们(如果可能)。
My question is: How do i make all those regressions with all by two combinations of the regressors? 我的问题是:如何通过回归变量的两个组合对所有这些回归进行回归?
You can use combn
for all the combinations and then use an apply
to create all the formulas: 您可以使用
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 = '+')))
Output 产量
> text_form
[1] "Y ~ a+b" "Y ~ a+c" "Y ~ a+d" "Y ~ a+e" "Y ~ a+f" "Y ~ a+g".....
Then you can feed the above formulas into your regression using as.formula
to convert the texts into formulas (most likely in another apply
). 然后,您可以使用
as.formula
将上述公式输入到回归中,以将文本转换为公式(最有可能在另一个apply
)。
You could also put them into formulas in one line like this: 您也可以将它们放在公式的一行中,如下所示:
mySpecs <- combn(letters[1:3], 2, FUN=function(x) reformulate(x, "Y"),
simplify=FALSE)
which returns a list that can be used in lapply
to run regressions: 它返回一个可以在
lapply
用于运行回归的列表:
mySpecs
[[1]]
Y ~ a + b
<environment: 0x4474ca0>
[[2]]
Y ~ a + c
<environment: 0x4477e68>
[[3]]
Y ~ b + c
<environment: 0x447ae38>
You would then do the following to get a list of regression results. 然后,您将执行以下操作以获取回归结果列表。
myRegs <- lapply(mySpecs, function(i) lm(i, data=df))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.