parse Function in R (Example)

This page shows how to convert a character string to an expression with the parse() function in the R programming language.

Example Data

Create character string in R:

my_expression_string <- "3 + 8"                      # Create string containing expression
# "3 + 8"

Check the class of our character string:

class(my_expression_string)                          # Check class of my_expression_string
# "character"

Convert Character String to Expression (parse Function)

Converting character string to expression:

my_expression <- parse(text = my_expression_string)  # Apply parse function
# expression(3 + 8)

Checking the class:

class(my_expression)                                 # Check class of my_expression
# "expression"

Our converted data object is an expression object. We now could apply functions such as eval to our expression:

eval(my_expression)                                  # Evaluate expression
# 11

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed