R 关于lm中逐步变量选择的失败

R 关于lm中逐步变量选择的失败,r,statistics,regression,lm,R,Statistics,Regression,Lm,我首先使用所有变量建立了一个回归模型 full.model<-lm(y~as.matrix(x)) 您不正确地使用了lm(…)。通常,最好通过引用数据框中的列来构建模型公式。试着这样做: # example data - you have this already... set.seed(1) # for reproducible example x <- sample(1:500,500) # need this so predictors are not

我首先使用所有变量建立了一个回归模型

full.model<-lm(y~as.matrix(x))

您不正确地使用了
lm(…)
。通常,最好通过引用数据框中的列来构建模型公式。试着这样做:

# example data - you have this already...
set.seed(1)            # for reproducible example
x <- sample(1:500,500) # need this so predictors are not perfectly correlated.
x <- matrix(x,nc=5)    # 100 rows, 5 cols
y <- 1+ 3*x[,1]+2*x[,2]+4*x[,5]+rnorm(100)  # y depends on variables 1, 2, 5 only

# you start here...
df <- data.frame(y,as.matrix(x))
full.model <- lm(y ~ ., df)                 # include all predictors
step(full.model,direction="backward")
# Start:  AIC=3.32
# y ~ X1 + X2 + X3 + X4 + X5
# ...
#
# Step:  AIC=1.38
# y ~ X1 + X2 + X3 + X5
# ...
# 
# Step:  AIC=-0.53
# y ~ X1 + X2 + X5
# 
#        Df Sum of Sq    RSS    AIC
# <none>                  92  -0.53
# - X2    1     53912  54004 635.16
# - X1    1    110870 110961 707.18
# - X5    1    235260 235352 782.37
#
# Call:
# lm(formula = y ~ X1 + X2 + X5, data = df)
# 
# Coefficients:
# (Intercept)           X1           X2           X5  
#       1.367        2.998        2.006        3.997  
#示例数据-您已经有了这个。。。
设定种子(1)#用于可复制的示例

这里的问题到底是什么?您试图浏览数据集,但函数在第一步就停止了?如果是这样的话,你可能会认为你已经找到了一个最佳的……逐步回归通常不是一个首选的技术。在花很多时间做这件事之前,你应该检查一下其他的选择。嗨,rnso,你能给我一些建议吗?谢谢。嗨,罗曼,这一步的结果让我很困惑。看起来它在原始完整模型上停止。但可以肯定的是,整个模型有太多的预测变量。我不清楚为什么step在这里不起作用。
> reduce.model<-step(full.model,direction="backward")
   Start:  AIC=-121.19
   y ~ as.matrix(x)

                 Df   Sum of Sq        RSS     AIC
  <none>                               1.1 -121.19
   - as.matrix(x) 37     21550         21550.7  310.36
# example data - you have this already...
set.seed(1)            # for reproducible example
x <- sample(1:500,500) # need this so predictors are not perfectly correlated.
x <- matrix(x,nc=5)    # 100 rows, 5 cols
y <- 1+ 3*x[,1]+2*x[,2]+4*x[,5]+rnorm(100)  # y depends on variables 1, 2, 5 only

# you start here...
df <- data.frame(y,as.matrix(x))
full.model <- lm(y ~ ., df)                 # include all predictors
step(full.model,direction="backward")
# Start:  AIC=3.32
# y ~ X1 + X2 + X3 + X4 + X5
# ...
#
# Step:  AIC=1.38
# y ~ X1 + X2 + X3 + X5
# ...
# 
# Step:  AIC=-0.53
# y ~ X1 + X2 + X5
# 
#        Df Sum of Sq    RSS    AIC
# <none>                  92  -0.53
# - X2    1     53912  54004 635.16
# - X1    1    110870 110961 707.18
# - X5    1    235260 235352 782.37
#
# Call:
# lm(formula = y ~ X1 + X2 + X5, data = df)
# 
# Coefficients:
# (Intercept)           X1           X2           X5  
#       1.367        2.998        2.006        3.997