I'm trying to replace characters in an R expression (not in a string), but it seems that the usual functions for replacing characters won't work in this case. For example, given the following:
exp <- expression(italic(N[T]))
class(exp) # "expression"
Both string::str_replace and base::gsub will fail to convert characters in this expression object. The first returning a warning message, and in both cases returning an object of class "character": the expression object is lost.
exp %>% stringr::str_replace(pattern = "T", replacement = "i")
[1] "italic(N[i])"
Warning message: In stri_replace_first_regex(string, pattern, fix_replacement(replacement), : argument is not an atomic vector; coercing
exp %>% base::gsub(pattern = "T", replacement = "i")
[1] "italic(N[i])"
Is it possible to convert characters in expressions without loosing the class type?
A trick like the following won't work:
exp %>% base::gsub(pattern = "N", replacement = "i") %>% base::gsub(pattern = "^", replacement ="expression(") %>% base::gsub(pattern = "$", replacement = ")")