5

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.

2
  • Your general approach is not going to work for you. If you try your code with words <- "frac{A}{B}" you get Error in parse(text = words) : <text>:1:5: unexpected '{' 1: frac{ Commented Oct 8, 2015 at 19:50
  • @ShawnMehan -- Yeah, I tried that, too. It seems that there should be some general way to do this, like sprintf or something, but I can't figure it out. Thanks. Commented Oct 8, 2015 at 19:52

3 Answers 3

3

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}"
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.