let me jump right into the example. Consider the following equation:
frml <- formula(y ~ a + b | x + z )
Such a formula specification is used e.g. with AER::ivreg
.
I would like to update this formula so that it reads
frml2 <- y ~ a + b + c | x + z + w
However, I am not sure how to update the parts before and after the conditional sign |
separately. For instance,
frml2 <- update.formula(frml, . ~ . + c | . + w)
gives
y ~ ((a + b | x + z) + c | (a + b | x + z) + w)
which is not quite what I want. The problem is that .
refers to the entire formula on the right (or left) side, including the conditional. Does anyone have an idea how I can update the formula accordingly?
One way seems to be to convert the formula into a character vector, split the vector at |
, add whatever I want to add, and put the formula back together. While this is easy, somehow I feel that there must be an easier way to do so. I surely am not the first person to deal with this kind of issue. Any advice / hint / comment would be greatly appreciated!
Can't tell for sure from your question if you cannot use a package, because the Formula
package has a function just for this. It classes its objects as both formula
and Formula
:
> library(Formula)
> frml <- Formula(y ~ a + b | x + z )
> update(frml, . ~ . + c | . + w)
y ~ a + b + c | x + z + w
> class(frml)
[1] "Formula" "formula"