Sapiens
Sapiens

Reputation: 1901

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

Upvotes: 1

Views: 826

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270288

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

Upvotes: 1

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9666

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

Upvotes: 0

Related Questions