Reputation: 21
I am working on a stepwise regression but am running into an error at the forward step:
Error in terms.default(object) : no terms component nor attribute
And I am not sure what to do about it.
Here is my code:
FullModel <- glm(Disease ~ age2 + Race2 + Gender + Lab1+ Lab2 + Lab3 + Lab4 +Lab5 + Lab6 + Lab7, family=binomial, data=Data)
EmptyModel <- glm(Disease ~ 1, family=binomial, data=Data)
Data<-na.omit(Data)
backwards = step(FullModel)
formula(backwards)
Data$forwards <- step(Data$EmptyModel,scope=list(lower=Data$EmptyModel,upper=Data$FullModel), direction="forward")
Error:
terms.default(object) : no terms component nor attribute
To trouble shoot, I checked to make sure that the class of the objects used were correct:
> class(EmptyModel)
[1] "glm" "lm"
> class(FullModel)
[1] "glm" "lm"
Any suggestions? Thank you kindly, in advance.
Upvotes: 2
Views: 20755
Reputation: 226881
You have to read the documentation carefully - this is admittedly not easy.
scope: defines the range of models examined in the stepwise search. This should be either a single formula, or a list containing components ‘upper’ and ‘lower’, both formulae. See the details for how to specify the formulae and how they are used.
The set of models searched is determined by the ‘scope’ argument. The right-hand-side of its ‘lower’ component is always included in the model, and right-hand-side of the model is included in the ‘upper’ component. If ‘scope’ is a single formula, it specifies the ‘upper’ component, and the ‘lower’ model is empty. If ‘scope’ is missing, the initial model is used as the ‘upper’ model.
Models specified by ‘scope’ can be templates to update ‘object’ as used by ‘update.formula’. So using ‘.’ in a ‘scope’ formula means ‘what is already there’, with ‘.^2’ indicating all interactions of existing terms.
This means that the elements of scope must be formulas (or "formulae" if your prefer ...)
So if you had a full additive model:
set.seed(101)
dd <- data.frame(y=rbinom(100,size=1,prob=0.5),
x1=rnorm(100),
x2=rnorm(100),
x3=rnorm(100),
x4=rnorm(100))
FullModel <- glm(y ~ x1+x2+x3+x4, family=binomial, data=dd)
EmptyModel <- update(FullModel, . ~ 1)
Since I made up random data, the stepwise procedure throws everything away ...
backwards = step(FullModel)
formula(backwards) ## y ~ 1
Forward stepwise regression:
forwards = step(EmptyModel, scope=list(lower=.~1,
upper=formula(FullModel)),
direction="forward")
Forward stepwise regression also ends up with the trivial model.
formula(forwards) ## y ~ 1
As a shortcut, if you want an additive model including all of the variables in the data except the response, you can just use glm(y~. , ...)
; this also works as a formula in the scope
argument (as described in the documentation)
Upvotes: 1