What is the parse() function in R?

Overview

The parse() function in R is used to return the parsed but unevaluated expression of a given expression.

Syntax

The syntax for the parse() function is given below:

parse(file = "", n = NULL, text = NULL, prompt = "?",
keep.source = getOption("keep.source"),
encoding = "unknown")
Syntax for the parse() function in R

Parameter value

The parse() function takes the following parameter values:

  • file (optional): This is a character string specifying the name of the file 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.

Return value

The parse() function returns an object type "expression".

Example

# A code to illustrate the parse() function
# creating a character vector
expr <- '5 * 2'
# calling the parse() function
parsed <- parse(text = expr)
# obtaining the object type
typeof(parsed)
# evaluating the parsed object
eval(parsed)

Explanation

  • Line 3: We create a character vector, expr.
  • Line 6: We call the parse() function and pass expr as the argument to the function. The result is assigned to a variable, parsed.
  • Line 9: We obtain the object type of the variable parsed by using the typeof() function.
  • Line 12: We evaluate the object parsed using the eval() function.

Free Resources