How to convert an expression into a string using deparse() in R

Overview

The deparse() function in R is used to convert an expression into a character string.

Syntax

deparse(expr)
Syntax for the deparse() function

Parameter value

The deparse() function takes the parameter value expr(), which represents the R expression that needs to be converted into a character string.

Return value

The deparse() function returns an object of the character class.

Code example

# creating an expression
expr = expression(5 ^ 2)
# evaluating the expression
eval(expr)
# calling the deparse() function
mychar = deparse(expr)
# evaluating the value of mychar
mychar
# checking the class of the result
class(mychar)

Code explanation

  • Line 2: We create an expression variable expr, using the expression() function.
  • Line 5: We evaluate the value of the expression in expr(), using the eval() function.
  • Line 8: We implement the deparse() function on the expression we created in expr. We assign the result to a variable called mychar.
  • Line 11: We print the variable mychar.
  • Line 14: We obtain the class of the variable mychar.

Free Resources