4

Is there a way to parse and evaluate a quosure from a string. I would like to achieve the same output as in the example below:

library(rlang)
a <- 10
quo(UQ(a) + 2 * b)
## <quosure: global>
## ~10 + 2 * b

but starting from

t <- "UQ(a) + 2 * b"

What I tried so fare is:

# Trial 1:
quo(expr(t))

# Trial 2: 
parse_quosure(t)

# Trial 3:
quo(parse_quosure(t))
johannes
  • 14,043
  • 5
  • 40
  • 51

2 Answers2

4

It looks like this may be a job for expr_interp. According to the documentation it "manually processes unquoting operators in expressions...".

So you can first use parse_quosure and then process the unquoting operators via expr_interp.

expr_interp(parse_quosure(t))

<quosure: global>
~10 + 2 * b
aosmith
  • 34,856
  • 9
  • 84
  • 118
  • 1
    It seems that `rlang::parse_quosure` has been superceeded by `rlang::parse_quo` and now requires an `env=` argument to be supplied. See https://search.r-project.org/CRAN/refmans/rlang/html/parse_expr.html – ekatko1 Mar 23 '23 at 16:45
2

One way would be to use parse to convert t to expression and eval to evaluate it.

eval(parse(text = paste0("quo(",t,")")))
#<quosure: global>
#~10 + 2 * b
d.b
  • 32,245
  • 6
  • 36
  • 77