Open In App

parse() Function in R

Improve
Improve
Like Article
Like
Save
Share
Report

The parse() function in R programming language is used to return the parsed but unevaluated expression of a given expression in an expression, a “list” of calls. Also, this function converts an R object of the character class to an R object of the expression class.

Syntax: parse(file = “”,  n = NULL, text = NULL, prompt = “?”, keep.source = getOption(“keep.source”), encoding = “unknown”)

Parameters:

  •    file (optional): This is a character string specifying the file’s name or the URL from which to read the expressions.
  •    n (optional): This is an integer representing the maximum number of expressions to be parsed.
  •    text (required): This is a character vector representing the text to be parsed.
  •    prompt (optional): This represents the prompt to return when parsing from the keyboard.
  •    keep.source (optional): This takes a logical value (True or False) indicating whether the source information is kept or not.
  •    encoding (optional): This is the encoding that is assumed for the input strings.

Returns: The parse() function returns an object type “expression”.

Example 1:

In this example, we will convert the provided data object from a character class to an expression class using the parsed function. Further, we will evaluate the converted expression in the R programming language.

R




# creating a character string
x <-"50/5"
 
# Changing the character to
# expression class
y <- parse(text = x)
 
# verifying the object type
class(y)
 
# evaluating the expression
eval(y)


Output:

'expression'
10

Example 2:

In this example, we will convert the provided data object of a character class with a long-expression to an expression class using the parsed function. Further, we will evaluate the converted expression in the R programming language.

R




# creating a character string
x1 <-"50/5+5^5-9*2"
 
# Changing the character to
# expression class
y1 <- parse(text = x1)
 
# verifying the object type
class(y1)
 
# evaluating the expression
eval(y1)


Output:

'expression'
3117

Last Updated : 18 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads