Lei Hao
Lei Hao

Reputation: 799

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

After running 'stepAIC', I have following result.

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

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

I have another forecast vector z=(z1,...,z5). Because it's part of for loop, I want to compute the forecast y automatically using 'coef %*% z'.

I could think of two ways to make it happen:
1. make the unselected coefficients of stepAIC to be 0; so instead of

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

I have

   coef=c(5,1,0,3,0,5)
  1. find the selected coefficients and find the corresponding 'z_i'.

I have no idea how to implement this. Any help would be appreciated. Thanks in advance.

Upvotes: 1

Views: 493

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73265

step method / facility returns just another lm object, so you can apply any generic functions, including predict to it.

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

If the final aim is not prediction, but as your question title states, use attr(terms(fit2), 'term.labels').

Upvotes: 1

Related Questions