简体   繁体   中英

Replace variable name in string with variable value [R]

I have a character in R, say "\\\\frac{A}{B}" . And I have values for A and B , say 5 and 10 . Is there a way that I can replace the A and B with the 5 and 10 ?

I tried the following.

words <- "\\frac{A}{B}"
numbers <- list(A=5, B=10)
output <- do.call("substitute", list(parse(text=words)[[1]], numbers))

But I get an error on the \\ . Is there a way that I can do this? I an trying to create equations with the actual variable values.

You could use the stringi function stri_replace_all_fixed()

stringi::stri_replace_all_fixed(
    words, names(numbers), numbers, vectorize_all = FALSE
)
# [1] "\\frac{5}{10}"

尝试这个:

sprintf(gsub('\\{\\w\\}','\\{%d}',words),5,10)

I'm more familiar with gsub than substitute . The following works:

words <- "\\frac{A}{B}"
numbers <- list(A=5, B=10)
arglist = mapply(list, as.list(names(numbers)), numbers, SIMPLIFY=F)
for (i in 1:length(arglist)){
    arglist[[i]]["x"] <- words
    words <- do.call("gsub", arglist[[i]])
}

But of course this is unsafe because you're iterating over the substitutions. If, say, the first variable has value "B" and the second variable has name "B", you'll have problems. There's probably a cleaner way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM