R has a handy tool for manipulating formulas, update.formula()
. This works nicely when you want to get something like "formula containing all terms in previous formula except x
", e.g.
f1 <- z ~ a + b + c
(f2 <- update.formula(f1, . ~ . - c))
## z ~ a + b
However, this doesn't seem to work with offset terms:
f3 <- z ~ a + offset(b)
update(f3, . ~ . - offset(b))
## z ~ a + offset(b)
I've dug down as far as terms.formula
, which ?update.formula
references:
[after substituting, ...] The result is then simplified via ‘terms.formula(simplify = TRUE)’.
terms.formula(z ~ a + offset(b) - offset(b), simplify=TRUE)
## z ~ a + offset(b)
(i.e., this doesn't seem to remove offset(b)
...)
I know I can hack up a solution either by using deparse()
and text-processing, or by processing the formula recursively to remove the term I don't want, but these solutions are ugly and/or annoying to implement. Either enlightenment as to why this doesn't work, or a reasonably compact solution, would be great ...
terms.formula
suggests that it explicitly preserves the offset term, although this doesn't seem to be documented anywhere as yet ... – Drift?offset
the documentation says"There can be more than one offset in a model formula, but - is not supported for offset terms (and is equivalent to +)."
. Could this be the reason as youroffset()
terms aren't simplifying? – Equalityoffset(-b)
instead? Your formula won't look simplified but I think the effect should be the same. If you trylm(mpg~cyl,data=mtcars);lm(mpg~cyl+offset(disp),data=mtcars);lm(mpg~cyl+offset(disp) + offset(-disp),data=mtcars);
You see the 1st and 3rdlm()
s are the same. – Equality