MyQ
MyQ

Reputation: 469

Removing the interaction terms when the main effect is removed

I have a formula in R for example

y ~ x + z + xx + zz + tt + x:xx + x:zz + xx:z + zz:xx + xx:zz:tt

or even more complicated (y~x*z*xx*zz*tt)

Note that the names on the right-hand side of the formula are intentionally selected to be somehow similar to at least one other term.

The question is now how to remove the interaction terms that are related to a specific main effect. For example, if I remove the term x (main effect) I want to remove the interaction terms that also include x, here x:xx.

I have tried grepl() but it would remove any term that contains partially or fully the word. In my example it removes x,xx,x:xx,xx:z,zz:xx,xx:zz:tt

any ideas about a function to do it?

Update: What I have already tried:

f = y ~ x + z + xx + zz + tt + x:xx + x:zz + xx:z + zz:xx + xx:zz:tt
modelTerms = attr(terms(f)    , which = 'term.labels')
modelTerms[!grepl(pattern = 'x', x = modelTerms)]

Upvotes: 1

Views: 280

Answers (3)

Roland
Roland

Reputation: 132706

Use update.formula:

f <- y~x*z*xx*zz*tt
update(f, . ~ . - x - x:.)
#y ~ z + xx + zz + tt + z:xx + z:zz + xx:zz + z:tt + xx:tt + zz:tt + 
#  z:xx:zz + z:xx:tt + z:zz:tt + xx:zz:tt + z:xx:zz:tt

f <- y ~ x + z + xx + zz + tt + x:xx + x:zz + xx:z + zz:xx + xx:zz:tt
update(f, . ~ . - x - x:.)
#y ~ z + xx + zz + tt + z:xx + xx:zz + xx:zz:tt

Upvotes: 4

TPArrow
TPArrow

Reputation: 1584

Simple:

f = y~x*z*xx*zz*tt
modelTerms = attr(terms(f)    , which = 'term.labels')


l = sapply(
    strsplit(x = modelTerms, split = '[:*]'),
    FUN = function(x) {
        'x' %in% x
    }
)
modelTerms[!l]

Upvotes: 1

jay.sf
jay.sf

Reputation: 72974

Are you looking for this?

> modelTerms[!grepl(pattern='^x\\:x+', x=modelTerms)]
[1] "x"        "z"        "xx"       "zz"       "tt"       "x:zz"     "z:xx"     "xx:zz"   
[9] "xx:zz:tt"

Upvotes: 1

Related Questions