18.13 Parsing and deparsing

  • Parsing - turning characters you’ve typed into an AST.
  • R usually takes care of parsing code for us.
  • But occasionally you have code stored as a string, and you want to parse it yourself.
  • You can do so using rlang::parse_expr():
x1 <- "y <- x + 10"
x1
# [1] "y <- x + 10"
is.call(x1)
# [1] FALSE
x2 <- rlang::parse_expr(x1)
x2
# y <- x + 10
is.call(x2)
# [1] TRUE
  • parse_expr() always returns a single expression.
  • If you have multiple expression separated by ; or , you’ll need to use rlang::parse_exprs(). It returns a list of expressions:
x3 <- "a <- 1; a + 1"
rlang::parse_exprs(x3)
# [[1]]
# a <- 1
# 
# [[2]]
# a + 1
# 
  • If you do this a lot, quasiquotation may be a safer approach.
    • More about this in Chapter 19.
  • The inverse of parsing is deparsing.
  • Deparsing - given an expression, you want the string that would generate it.
  • This happens automatically when you print an expression.
  • You can get the string with rlang::expr_text():
  • Parsing and deparsing are not symmetric.
    • Parsing creates the AST.
z <- expr(y <- x + 10)
expr_text(z)
#> [1] "y <- x + 10"