1

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

Karolis Koncevičius
  • 7,687
  • 9
  • 48
  • 71
Sapiens
  • 1,259
  • 2
  • 11
  • 17

2 Answers2

1

Assume that v is a term by itself (which is the case in the question) and the inputs shown in the Note at the end. Then here are two approaches.

1) update Use reformulate to create the formula ~ . - v + a + b + c and update the input formula with it.

update(fo, reformulate(c(". - v", var, covar)))
## condition ~ (1 | subject) + a + b + c

2) getTerms Another approach is to decompose the formula into terms using getTerms from this post, remove v, append var and covar and reformulate it back into a formula:

reformulate(c(setdiff(sapply(getTerms(fo[[3]]), format), "v"), var, covar), fo[[2]])
## condition ~ (1 | subject) + a + b + c

Note

The inputs are assumed to be:

var <- 'a'
covar <- c('b', 'c')
fo <- condition ~ (1 | subject) + v
G. Grothendieck
  • 211,268
  • 15
  • 177
  • 297
  • I was using 'v' as a placeholder in the specific case of the substitute() function. Overall this solution also works for the problem I have in hand with formulas for linear models. – Sapiens Jan 10 '21 at 17:25
  • If it is good enough just to add on `var` and `covar` you wouldn't really need a placeholder in which case it would be sufficient to use: `fo2 – G. Grothendieck Jan 10 '21 at 17:30
  • Also if we can assume that the input is the character vector `x – G. Grothendieck Jan 11 '21 at 12:52
0

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
Karolis Koncevičius
  • 7,687
  • 9
  • 48
  • 71