R eval Function (3 Examples) | Evaluate Expressions & Character Strings
In this R tutorial, I’ll explain how to evaluate an expression with the eval function. Let’s first have a look at the basic R syntax and the definition of eval:
Basic R Syntax:
The eval function evaluates (i.e. calculates) an R expression and returns the result.
In the following, I’ll show you three examples how to apply and how not to apply the eval function in R. So let’s move straight to the examples…
Example 1: Basic application of the eval() Function in R
The eval R function is usually applied to an expression. So let’s create such an expression first:
x1 <- expression(3 * 5) # Create example expression x1 # expression(3 * 5)
Our example data object x1 contains the expression 3 * 5.
If we want to get the result of this expression (i.e. evaluate the expression), we can use the eval command as follows:
eval(x1) # Evaluate expression with eval() # 15
As you can see, the eval function returned 15 (the result of 3 * 5) to the RStudio console.
Example 2: Evaluate Expression Given as Character String
Expressions are often stored as R character string. Let’s create such a character string in R:
x2 <- "3 * 5" # Create expression as character string # "3 * 5"
With the class function, we can also check the class of our example data x2:
class(x2) # Check class of example character # "character"
Since the eval function is not capable of evaluating character strings, we need to convert the character class to the expression class first. We can do that with the parse function as follows:
eval(parse(text = x2)) # Parse character before using eval # 15
As before the evaluation of our expression results in the value 15. Looks good!
Example 3: R Error in eval: Object not Found
A typical error, that occurs when the eval function is used, is the following:
Error in eval(x) : object ‘x’ not found
This error appears when the eval function is applied to non-existent data objects. We can see that based on the following R code:
eval(x3) # Apply eval to non-existent data object # Error in eval(x3) : object 'x3' not found
Table 1: Error in eval Function: Object not Found.
We applied the eval command to x3, a data object that doesn’t exist. This error might be obvious to you, but however, when eval is applied in more complex situations (e.g. in loops, for a variable in a data frame, or in combination with R Markdown) this error message occurs regularly.
Keep this in mind, then it’s easy to avoid it!
Video: Alternatives to the eval Function
The eval function is often used when unstructured text documents need to be analyzed. If you want to learn more about the handling of text data, you should have a look at the following YouTube video of Tomer Ben David. In the video, he explains different functions for the treatment and evaluation of text data.