Search code examples
rformula

update formula to add functions of covariates


Suppose that we have a formula

f1 <- y ~ x1

and that we need to add to it the covariate sin(2*pi*x2) using a function that will take as argument x2.

Of course, this works: update(f1, . ~ . + sin(2 * pi * x2) but I need a function likes this one

updf <- function(formula, x){
    formula <- update(formula, paste("~ . +", sin(2 * pi * x)))
    formula}

and the call updf(f1,"x2") will return: y ~ x1 + sin(2 * pi * x2). This call returns "Error in 2 * pi * x : non-numeric argument to binary operator".

How can this problem be fixed?


Solution

  • If x is a string with the name of the variable then formula <- update(formula, paste("~ . + sin(2 * pi * ", x, ")")) should work.

    f1 <- y ~ x1
    
    updf <- function(formula, x){
      formula <- update(formula, paste("~ . + sin(2 * pi * ", x, ")"))
      formula
    }  
    
    updf(f1, "x2")
    #> y ~ x1 + sin(2 * pi * x2)
    

    This answer comes from @Oliver's comment and was posted more than a month after. I don't want to steal credit, I just want this question to stop appearing as "unanswered" while it is actually answered.