I'm curious to know if R can use its eval()
function to perform calculations provided by e.g. a string.
This is a common case:
eval("5+5")
However, instead of 10 I get:
[1] "5+5"
Any solution?
I'm curious to know if R can use its eval()
function to perform calculations provided by e.g. a string.
This is a common case:
eval("5+5")
However, instead of 10 I get:
[1] "5+5"
Any solution?
You can use the
parse()
function to convert the characters into an expression. You need to specify that the input is text, because parse expects a file by default:The
eval()
function evaluates an expression, but"5+5"
is a string, not an expression. Useparse()
withtext=<string>
to change the string into an expression:Calling
eval()
invokes many behaviours, some are not immediately obvious:See also tryCatch.
Alternatively, you can use
evals
from mypander
package to capture output and all warnings, errors and other messages along with the raw results:Sorry but I don't understand why too many people even think a string was something that could be evaluated. You must change your mindset, really. Forget all connections between strings on one side and expressions, calls, evaluation on the other side.
The (possibly) only connection is via
parse(text = ....)
and all good R programmers should know that this is rarely an efficient or safe means to construct expressions (or calls). Rather learn more aboutsubstitute()
,quote()
, and possibly the power of usingdo.call(substitute, ......)
.Dec.2017: Ok, here is an example (in comments, there's no nice formatting):
and if you get more experienced you'll learn that
q5
is a"call"
wherease5
is an"expression"
, and even thate5[[1]]
is identical toq5
:Nowadays you can also use
lazy_eval
function fromlazyeval
package.