obug obug - 5 months ago 23
R Question

Using a variable in update() in R to update formula

I am trying to add term to a model formula in R. This is straightforward to do using update() if I enter the variable name directly into the update function. However it does not work if the variable name is in a variable.

myFormula <- as.formula(y ~ x1 + x2 + x3)
addTerm <- 'x4'

#Works: x4 is added
update(myFormula, ~ . + x4)
Output: y ~ x1 + x2 + x3 + x4

#Does not work: "+ addTerm" is added instead of x4 being removed
update(myFormula, ~ . + addTerm)
Output: y ~ x1 + x2 + x3 + addTerm

Adding x4 via the variable can be done in a slightly more complex way.

formulaString <- deparse(myFormula)
newFormula <- as.formula(paste(formulaString, "+", addTerm))
update(newFormula, ~.)
Output: y ~ x1 + x2 + x3 + x4

Is there a way to get update() to do this directly without needing these extra steps? I've tried paste, parse, and the other usual functions and they don't work.

For example, if paste0 is used the output is

update(myFormula, ~ . + paste0(addTerm))
Output: y ~ x1 + x2 + x3 + paste0(addTerm)

Does anybody have any recommendations on how to use a variable in update()?



You can probably just do:

update(myFormula, paste("~ . +",addTerm))