evaluate expression in data.table

流过昼夜 提交于 2021-02-10 18:35:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!