1

Say, for example, you have the following string:

"(1+1)*2"

And you want to transform it to its actual value (4, which comes from evaluating the equation in the string) in numeric.

I've trayed several ways, using eval() or as.formula(), but haven't figured it out yet. Any guess?

  • Nor as.numeric, I find...hmmh. @zephryl, could you expand on 'sanitizing inputs', are we talking SQL injection or the like? – Chris Dec 29 '22 at 04:28

2 Answers2

1

You can use eval(parse()) as follows:

eval(parse(text = "(1+1)*2"))
# 4

Note you shouldn’t use this in a public-facing application without sanitizing inputs.

zephryl
  • 14,633
  • 3
  • 11
  • 30
  • And might you expand on sanitizing inputs, as cautionary tales are always useful as choices are made in approaches, i.e. what would sanitizing look like in this instance? – Chris Dec 29 '22 at 04:32
  • 1
    Without scary details, something like `eval(parse(text = "code.to.kill.the.computer()"))` may do harm to your computer. An input with only numbers, brackets, and arithmetic operators is probably safe. – Andrey Shabalin Dec 29 '22 at 04:35
  • @Chris [this thread](https://stackoverflow.com/q/18369913/17303805) has more info on potential issues and solutions. tbh I’m not super knowledgeable in this area beyond knowing you should generally be careful with anything evaluating arbitrary code. – zephryl Dec 29 '22 at 04:50
0

parse(text = "...") is equivalent to str2lang("...").

eval(str2lang("(1+1)*2"))

# [1] 4
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51