Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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()?

Thanks

like image 724
obug Avatar asked Aug 16 '16 16:08

obug


People also ask

How do you update a variable in R?

The mutate() function is used to modify a variable or recreate a new variable. Variable are changed by using the name of variable as a parameter and the parameter value is set to the new variable.

What is the update function in R?

update will update and (by default) re-fit a model. It does this by extracting the call stored in the object, updating the call and (by default) evaluating that call. Sometimes it is useful to call update with only one argument, for example if the data frame has been corrected.


1 Answers

You can probably just do:

update(myFormula, paste("~ . +",addTerm))
like image 67
joran Avatar answered Sep 28 '22 04:09

joran