如何在 R 的 stepAIC 中自动知道所选变量?

How to automatically know the selected variable in stepAIC in R?

在 运行 'stepAIC' 之后,我得到了以下结果。

 fit1=lm(y~ x1+x2+x3+x4+x5)
 fit2=stepAIC(fit1)
 coef=fit2$coefficients

 >coef
 >intercept, x1,  x3,  x5
       5      1,    3,   5

我有另一个预测向量 z=(z1,...,z5)。因为它是 for 循环的一部分,所以我想使用 'coef %*% z'.

自动计算预测 y

我可以想到两种方法来实现它:
1. 将stepAIC未选择的系数设为0;所以而不是

   coef=c(5,1,3,5)

我有

   coef=c(5,1,0,3,0,5)
  1. 找到选中的系数,找到对应的'z_i'.

我不知道如何实现它。任何帮助,将不胜感激。提前致谢。

step 方法/设施 returns 只是另一个 lm object,因此您可以应用任何通用函数,包括 predict

predict(fit2, newdata = a.data.frame)

如果最终目标不是预测,而是如您的问题标题所述,请使用 attr(terms(fit2), 'term.labels')