Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formula manipulation (place interaction terms in proper order)

Tags:

r

formula

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?

like image 687
devdreamer Avatar asked Aug 26 '15 00:08

devdreamer


1 Answers

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().

like image 182
Rich Scriven Avatar answered Oct 04 '22 11:10

Rich Scriven