David
David

Reputation: 345

Get variable names from an lm object without segregating factor levels

I need to get variables names back form an lm model. variable.names() does fine except when one of the variables is a factor, in that case:

model <- lm(Petal.Length~Petal.Width+Species, data=iris)
variable.names(model)

returns:

"(Intercept)"       "Petal.Width"       "Speciesversicolor"        "Speciesvirginica" 

I need the Speciesvariable to appear only once, without specifying different levels for each factor, something like:

"(Intercept)"       "Petal.Width"       "Species" 

Upvotes: 1

Views: 1628

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270268

Get the names of the model's model.frame:

names(model.frame(model))
## [1] "Petal.Length" "Petal.Width"  "Species"   

or use terms

all.vars(terms(model))
## [1] "Petal.Length" "Petal.Width"  "Species" 

Upvotes: 4

jay.sf
jay.sf

Reputation: 73712

You could extract the names with all.vars from the call, remove the last string which is the data.

all.vars(model$call)[1:length(model$call)]
# [1] "Petal.Length" "Petal.Width"  "Species"  

Upvotes: 4

Related Questions