简体   繁体   中英

evaluate expression in data.table

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM