Replace the variable name in the string with the variable value [R]

I have a character in R, say "\\frac{A}{B}" . And I have values ​​for A and B , for example 5 and 10 . Is there a way to replace A and B with 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 message on \ . Is there a way I can do this? I am trying to create equations with actual variable values.

+5
source share
3 answers

You can use stringi function stri_replace_all_fixed()

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

Try the following:

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

I am 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 are repeating replacements. If, say, the first variable has the value "B" and the second variable has the name "B", you will have problems. There is probably a cleaner way.

+1
source

Source: https://habr.com/ru/post/1233283/


All Articles