Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 873
Richard Herron Avatar asked Oct 08 '15 19:10

Richard Herron


2 Answers

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}"
like image 187
Rich Scriven Avatar answered Nov 15 '22 00:11

Rich Scriven


Try this:

sprintf(gsub('\\{\\w\\}','\\{%d}',words),5,10)
like image 44
Shenglin Chen Avatar answered Nov 15 '22 01:11

Shenglin Chen