1

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.

Rafael
  • 3,096
  • 1
  • 23
  • 61

1 Answers1

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)) ]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @R.M. With `rlang` and tidyverse, they use a consistent pattern with `!!`, but that wouldn't work outside the tidyverse env or else you may need `as_mapper` – akrun Nov 22 '19 at 19:26