tags:

views:

432

answers:

3
+3  Q: 

R eval expression

Hi all,

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? :-)

A: 

google says eval(parse("5+5")) should work

just somebody
Nope, it doesn't. First argument of parse is a file connection.
Harlan
+3  A: 

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:

eval(parse(text="5+5"))
Shane
thanks a lot! I was missing that text step
Thrawn
+8  A: 

eval() evaluates an expression, but "5+5" is a string, not an expression. So, use parse() with text= to translate the string to an expression:

> eval(parse(text="5+5"))
[1] 10
> class("5+5")
[1] "character"
> class(parse(text="5+5"))
[1] "expression"
Harlan
brilliant, and thanks for the type explanation too :-)
Thrawn