Learn R Programming

evaluate (version 1.0.1)

parse_all: Parse, retaining comments

Description

Works very similarly to parse, but also keeps original formatting and comments.

Usage

parse_all(x, filename = NULL, allow_error = FALSE)

Value

A data frame two columns, src and expr, and one row for each complete input in x. A complete input is R code that would trigger execution when typed at the console. This might consist of multiple expressions separated by ; or one expression spread over multiple lines (like a function definition).

src is a character vector of source code. Each element represents a complete input expression (which might span multiple line) and always has a terminal \n.

expr is a list-column of expressions. The expressions can be of any length, depending on the structure of the complete input source:

  • If src consists of only only whitespace and/or comments, expr will be length 0.

  • If src a single scalar (like TRUE, 1, or "x"), name, or function call, expr will be length 1.

  • If src contains multiple expressions separated by ;, expr will have length two or more.

The expressions have their srcrefs removed.

If there are syntax errors in x and allow_error = TRUE, the data frame will have an attribute PARSE_ERROR that stores the error object.

Arguments

x

object to parse. Can be a string, a file connection, or a function. If a connection, will be opened and closed only if it was closed initially.

filename

string overriding the file name

allow_error

whether to allow syntax errors in x

Examples

Run this code
# Each of these inputs are single line, but generate different numbers of
# expressions
source <- c(
  "# a comment",
  "x",
  "x;y",
  "x;y;z"
)
parsed <- parse_all(source)
lengths(parsed$expr)
str(parsed$expr)

# Each of these inputs are a single expression, but span different numbers
# of lines
source <- c(
  "function() {}",
  "function() {",
  "  # Hello!",
  "}",
  "function() {",
  "  # Hello!",
  "  # Goodbye!",
  "}"
)
parsed <- parse_all(source)
lengths(parsed$expr)
parsed$src

Run the code above in your browser using DataLab