问题
I'm trying to evaluate a string as a formula:
In dplyr it would look like this:
dt = data.table(a = 1:10)
expr = 'sum(a)'
dt %>%
mutate(b := !!parse_expr(expr))
However when I try with data.table I'm getting an error:
dt[, b := parse_expr(expr)]
Error in
[.data.table(dt, ,:=(b, parse_expr(expr))) : RHS of assignment is not NULL, not an an atomic vector (see ?is.atomic) and not a list column.
回答1:
Instead of parse_expr, eval(parse can be used
dt[, b := eval(parse(text = expr))]
Or wrap with eval on parse_expr as the !! is doing the evaluation in tidyverse
dt[, b := eval(rlang::parse_expr(expr)) ]
来源:https://stackoverflow.com/questions/59000463/evaluate-expression-in-data-table