johannes
johannes

Reputation: 14433

Parse and evaluate quosures from string

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

Upvotes: 4

Views: 817

Answers (2)

aosmith
aosmith

Reputation: 36086

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

Upvotes: 4

d.b
d.b

Reputation: 32548

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

Upvotes: 2

Related Questions