Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate expression given as a string

Tags:

r

r-faq

eval

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?

like image 876
Federico Giorgi Avatar asked Nov 16 '09 17:11

Federico Giorgi


People also ask

What is expression evaluation in python?

Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer.


1 Answers

The eval() function evaluates an expression, but "5+5" is a string, not an expression. Use parse() with text=<string> to change the string into an expression:

> eval(parse(text="5+5")) [1] 10 > class("5+5") [1] "character" > class(parse(text="5+5")) [1] "expression" 

Calling eval() invokes many behaviours, some are not immediately obvious:

> class(eval(parse(text="5+5"))) [1] "numeric" > class(eval(parse(text="gray"))) [1] "function" > class(eval(parse(text="blue"))) Error in eval(expr, envir, enclos) : object 'blue' not found 

See also tryCatch.

like image 62
Harlan Avatar answered Sep 21 '22 04:09

Harlan