devdreamer
devdreamer

Reputation: 179

Formula manipulation (place interaction terms in proper order)

I am trying to build up a model validation tool in which I am following a forward selection approach, so if we suppose my model is

model <- y ~ a * b + c * d + e

I can use the terms function

attributes(terms(model))$term.labels

to find out all the predictors in my model, but the problem with this approach is that interactions terms always get put at the end of the result. I want a:b to be after a and b, and not at the end, and same goes for c:d. Is there a way to keep the order with the interaction terms?

Upvotes: 6

Views: 431

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99341

The simplest way would be to use keep.order in terms.formula()

model <- y ~ a * b + c * d + e
labels(terms(model, keep.order = TRUE))
# [1] "a"   "b"   "a:b" "c"   "d"   "c:d" "e"  

To look up the help file, you will want to use ?terms.formula, as this method is not shown in ?terms. But terms() will dispatch to the formula method. Additionally, labels() is a shorthand way to get the term labels from terms().

Upvotes: 9

Related Questions