rexpressionsubstitutionr-formula

R substitute(), to substitute values in expression, is adding unnecessary quotes


I am trying to update a formula for a linear model in R, based on names of variables that I have stored in an array. I am using substitute() for that and the code is as follows.

var = 'a'
covar = c('b', 'c')
covar = paste(c(var, covar), collapse = ' + ')
formula = substitute(condition ~ (1|subject) + v, list(v = as.name(covar)))
print(formula)

Output

condition ~ (1 | subject) + `a + b + c`

How do I remove the extra `` around a + b + c?

If I don't concatenate with paste, then it works, but I need those extra variables...

var = 'a'
formula = substitute(condition ~ (1|subject) + v, list(v = as.name(var)))
print(formula)

Output

condition ~ (1 | subject) + a

Both var and covar are char type.

Another solution that lets iteratively change v in formula that could also work


Solution

  • Maybe I misunderstood what you are doing, but the following seems to work:

    form  <- 'condition ~ (1|subject) + v'
    var   <- 'a'
    covar <- c('b', 'c')
    

    Then combine with paste and turn to formula directly:

    covar <- paste(var, paste(covar, collapse=" + "), sep=" + ")
    form  <- formula(paste(form, covar, sep=" + "))
    

    Output:

    condition ~ (1 | subject) + v + a + b + c