These functions parse and transform text into R expressions. This is the first step to interpret or evaluate a piece of R code written by a programmer.
parse_quosures(x, env = caller_env())parse_expr(x)
parse_exprs(x)
Text containing expressions to parse_expr for
parse_expr()
and parse_exprs()
. Can also be an R connection,
for instance to a file. If the supplied connection is not open,
it will be automatically closed and destroyed.
The environment for the quosures. Depending on the use case, a good default might be the global environment but you might also want to evaluate the R code in an isolated context (perhaps a child of the global environment or of the base environment).
parse_expr()
returns an expression,
parse_exprs()
returns a list of expressions.
parse_quosure()
and parse_quosures()
were soft-deprecated in
rlang 0.2.0 and renamed to parse_quo()
and parse_quos()
. This
is consistent with the rule that abbreviated suffixes indicate
the return type of a function.
parse_expr()
returns one expression. If the text contains more
than one expression (separated by semicolons or new lines), an error is
issued. On the other hand parse_exprs()
can handle multiple
expressions. It always returns a list of expressions (compare to
base::parse()
which returns an base::expression vector). All
functions also support R connections.
The versions suffixed with _quo
and quos
return
quosures rather than raw expressions.
# NOT RUN {
# parse_expr() can parse any R expression:
parse_expr("mtcars %>% dplyr::mutate(cyl_prime = cyl / sd(cyl))")
# A string can contain several expressions separated by ; or \n
parse_exprs("NULL; list()\n foo(bar)")
# You can also parse source files by passing a R connection. Let's
# create a file containing R code:
path <- tempfile("my-file.R")
cat("1; 2; mtcars", file = path)
# We can now parse it by supplying a connection:
parse_exprs(file(path))
# }
Run the code above in your browser using DataLab