[英]Constrain number of predictor variables in stepwise regression in R
I would like to be able to do a forward stepwise linear regression, but constrain the number of predictor variables to a maximum (in my specific case, three).我希望能够进行正向逐步线性回归,但将预测变量的数量限制为最大值(在我的特定情况下为三个)。 Here is some sample data.这是一些示例数据。
set.seed(123)
myDep <- runif(100)
pred1 <- myDep + runif(100)
pred2 <- myDep + rnorm(100)
pred3 <- myDep + runif(100) + rnorm(100)
pred4 <- myDep + runif(100) + runif(100)
pred5 <- runif(100)
myDF <- data.frame(myDep, pred1, pred2, pred3, pred4, pred5)
If I were to simply run a linear regression using the following code below, I would get all five predictor variables, obviously.如果我使用下面的代码简单地运行线性回归,显然我会得到所有五个预测变量。
myModel <- lm(myDep ~ ., data = myDF)
What I would like to do it use step() or other R command to run a forward-direction stepwise that picks only three predictor variables and then stops.我想做的事情是使用 step() 或其他 R 命令逐步运行正向运行,只选择三个预测变量然后停止。
For what it is worth, I tried this:对于它的价值,我试过这个:
step(lm(myDep ~ ., data = myDF), steps = 3, direction = "forward")
and the results were the following -- but not what I want because it uses all five predictor variables.结果如下——但不是我想要的,因为它使用了所有五个预测变量。
Start: AIC=-378.09
myDep ~ pred1 + pred2 + pred3 + pred4 + pred5
Call:
lm(formula = myDep ~ pred1 + pred2 + pred3 + pred4 + pred5, data = myDF)
Coefficients:
(Intercept) pred1 pred2 pred3 pred4 pred5
-0.16617 0.30043 0.07983 0.03670 0.17869 0.01606
I'm sure there's a way to do this, but I cannot seem to figure out the proper formatting.我确信有一种方法可以做到这一点,但我似乎无法弄清楚正确的格式。 Thanks in advance.提前致谢。
You could use the regsubsets package in R, where you can limit the variables and choose your method ("forward").您可以在 R 中使用 regsubsets 包,您可以在其中限制变量并选择您的方法(“转发”)。
https://www.rdocumentation.org/packages/leaps/versions/2.1-1/topics/regsubsets https://www.rdocumentation.org/packages/leaps/versions/2.1-1/topics/regsubsets
library(regsubsets)
b <- regsubsets(myDep ~ ., data=myDF, nbest=1, nvmax=[enter your max # of predictors])
summary(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.