我想对一组变量运行最佳子集回归,然后使用R得到最好的3个变量。我在获得最佳2个变量时遇到问题。我在下面提供了我的代码。
set.seed(10)
a <- 1:100
b <- 1:100
c <- 1:100
d <- 1:100
e <- 1:100
f <- 1:100
g <- 1:100
h <- 1:100
data <- data.frame(a, b, c, d, e, f, g, h)
library(leaps)
# best subsets regression
test <- regsubsets(a ~ b + c + d + e + f + g + h, data=data, nbest=4)
# nbest = 4, is the number of subsets of each size that is reported
# plot a table of models showing variables in each model.
summary(test)
# models are ordered by the selection statistic.
plot(test,scale="r2")
#get the variables that are important to the model
coef(test, 2)
#NOTE: THIS DOESN'T GIVE ME THE 2 BEST VARIABLES. IT ONLY GIVES ME THE BEST VARIABLE AT THE 2ND ITERATION. LOOK AT:
coef(test, 1:2)
非常感谢您的帮助!
最佳, 德纳
答案 0 :(得分:1)
考虑一个内置mtcars
数据集的示例:
test <- regsubsets(mpg ~ ., data = mtcars, nbest = 4)
这是summary(test)
的输出:
summary(test)
# Subset selection object
# Call: regsubsets.formula(mpg ~ ., data = mtcars, nbest = 4)
# 10 Variables (and intercept)
# <..snip..>
# 4 subsets of each size up to 8
# Selection Algorithm: exhaustive
# cyl disp hp drat wt qsec vs am gear carb
# 1 ( 1 ) " " " " " " " " "*" " " " " " " " " " "
# 1 ( 2 ) "*" " " " " " " " " " " " " " " " " " "
# 1 ( 3 ) " " "*" " " " " " " " " " " " " " " " "
# 1 ( 4 ) " " " " "*" " " " " " " " " " " " " " "
# 2 ( 1 ) "*" " " " " " " "*" " " " " " " " " " "
# 2 ( 2 ) " " " " "*" " " "*" " " " " " " " " " "
# 2 ( 3 ) " " " " " " " " "*" "*" " " " " " " " "
# 2 ( 4 ) " " " " " " " " "*" " " "*" " " " " " "
# 3 ( 1 ) " " " " " " " " "*" "*" " " "*" " " " "
# <..snip..>
系数集由自变量的数量排列,子集为4(我们用nbest
参数表示的);因此,coef(test, 1:4)
将返回具有一个独立变量的模型的系数,coef(test, 5:8)
将是具有两个独立变量的系数,依此类推。在每个子集中,最好的&#34;模特第一。最好的&#34;因此,具有两个自变量的模型将是模型5:
coef(test, 5)
# (Intercept) cyl wt
# 39.686261 -1.507795 -3.190972