Mir Henglin
Mir Henglin

Reputation: 669

Replacing a string in an R formula

I have a question about formula modification in R.

Lets say that I have a formula.

> fo <- a ~ b + c

I can substitute a term out using substitute_q

> pryr::substitute_q(fo, list(a = 'happy'))
"happy" ~ b + c

If I want to substitute a term in without quotation marks, I can substitute it in as a name

> pryr::substitute_q(fo, list(a = as.name('happy')))
happy ~ b + c

Now, however, lets say that I have a formula with a string.

> fo <- 'a' ~ b + c
> fo
"a" ~ b + c

I can't find a way to substitute the string out of the formula.

> pryr::substitute_q(fo, list(a = as.name('happy')))
"a" ~ b + c
> pryr::substitute_q(fo, list("a" = as.name('happy')))
"a" ~ b + c
> pryr::substitute_q(fo, list(`"a"` = as.name('happy')))
"a" ~ b + c
> pryr::substitute_q(fo, list('"a"' = as.name('happy')))
"a" ~ b + c

I think this is because substitute_q looks for variables within an environment when performing substitutions, which means that it always tries to replace names within the formula. Is there a way to substitute out the character 'a'?

Upvotes: 2

Views: 681

Answers (1)

d.b
d.b

Reputation: 32558

In base R, use deparse to convert formula to character, carry out the necessary substitution, and coerce back to formula

fo <- 'a' ~ b + c
as.formula(gsub("\"a\"", "\"happy\"", deparse(fo)))
#"happy" ~ b + c

fo2 = func1(a, b) ~ func2("e", 10) + b * c + func3(d)
as.formula(gsub("func2(\"e\", 10)", "func2(HAN, SOLO)", deparse(fo2), fixed = TRUE))
#func1(a, b) ~ func2(HAN, SOLO) + b * c + func3(d)

Upvotes: 1

Related Questions