Parse and evaluate quosures from string

779 Views Asked by At

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))
2

There are 2 best solutions below

1
On BEST ANSWER

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
0
On

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