eval Function in R (2 Examples)
This tutorial shows how to evaluate expressions with the eval() function in the R programming language.
Example 1: Apply eval Function to Expression Object
Example expression:
my_expression <- expression(3 + 8) # Create example expression my_expression # expression(3 + 8) |
my_expression <- expression(3 + 8) # Create example expression my_expression # expression(3 + 8)
Application of eval function:
eval(expression(3 + 8)) # Apply eval function to expression # 11 |
eval(expression(3 + 8)) # Apply eval function to expression # 11
The RStudio console returns 11, i.e. the result of our example expression 3 + 8.
Example 2: Apply eval Function to Character String
Example character string:
my_expression_string <- "3 + 8" # Create string containing expression my_expression_string # "3 + 8" |
my_expression_string <- "3 + 8" # Create string containing expression my_expression_string # "3 + 8"
If we want to evaluate an expression stored as character string, we need to combine the eval function with the parse function:
eval(parse(text = my_expression_string)) # Combined application of eval & parse # 11 |
eval(parse(text = my_expression_string)) # Combined application of eval & parse # 11
2 Comments. Leave new
Need a page to explain the differences among:
eval
parse
expression
text
Hey Lee,
Thank you for the comment! Unfortunately, I don’t have such a comparison page yet. You may have a look at this tutorial, though. It explains how to use the parse function in combination with the eval function.
Regards,
Joachim