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_expr(x)

parse_exprs(x)

parse_quosure(x, env = caller_env())

parse_quosures(x, env = caller_env())

Arguments

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.

env

The environment for the formulas. Defaults to the context in which the parse_expr function was called. Can be any object with a as_env() method.

Value

parse_expr() returns a formula, parse_exprs() returns a list of formulas.

Details

parse_expr() returns one expression. If the text contains more than one expression (separated by colons 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 prefixed with f_ return expressions quoted in formulas rather than raw expressions.

See also

base::parse()

Examples

# parse_expr() can parse_expr any R expression: parse_expr("mtcars %>% dplyr::mutate(cyl_prime = cyl / sd(cyl))")
#> 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)")
#> [[1]] #> NULL #> #> [[2]] #> list() #> #> [[3]] #> foo(bar) #>
# The versions suffixed with _f return formulas: parse_quosure("foo %>% bar()")
#> <quosure: local> #> ~foo %>% bar()
parse_quosures("1; 2; mtcars")
#> [[1]] #> <quosure: local> #> ~1 #> #> [[2]] #> <quosure: local> #> ~2 #> #> [[3]] #> <quosure: local> #> ~mtcars #>
# The env argument is passed to as_env(). It can be e.g. a string # representing a scoped package environment: parse_quosure("identity(letters)", env = empty_env())
#> <quosure: empty> #> ~identity(letters)
parse_quosures("identity(letters); mtcars", env = "base")
#> [[1]] #> <quosure: base> #> ~identity(letters) #> #> [[2]] #> <quosure: base> #> ~mtcars #>
# 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))
#> [[1]] #> [1] 1 #> #> [[2]] #> [1] 2 #> #> [[3]] #> mtcars #>