Skip to content
Prev 336182 / 398513 Next

update.formula() to add interaction terms

Is this the sort of thing you are looking for?
   > fm <- y ~ x1 + x2 + x3 + log(x4)
   > # Use terms() instead of just all.vars() to keep log(x4) as log(x4)
   > xVars <- with(attributes(terms(fm)), as.list(variables)[-c(1,response+1)])
   > str(xVars)
   List of 4
    $ : symbol x1
    $ : symbol x2
    $ : symbol x3
    $ : language log(x4)
   > # use bquote to make the addition to the formula
   > update(fm, bquote( ~ . + .(xVars[[1]]) * .(xVars[[length(xVars)]])))
   y ~ x1 + x2 + x3 + log(x4) + x1:log(x4)

As a function it would be
   addInteraction <- function(formula){
      xVars <- with(attributes(terms(formula)), as.list(variables)[-c(1,response+1)]) 
     update(formula, bquote( ~ . + .(xVars[[1]]) * .(xVars[[length(xVars)]])))
   }
used as
   > addInteraction(y~x1+x2+sqrt(x3))
   y ~ x1 + x2 + sqrt(x3) + x1:sqrt(x3)

If the last 'term' in the formula is a compound like x4:x5 and you
want x1:x4:x5 added you will need to do more work (look at the
'factors' attribute of terms()'s output) - currently it adds x1:x5.


Bill Dunlap
TIBCO Software
wdunlap tibco.com