1

I have a working R function written as:

library(data.table)
mutate_dt = function (.data, ..., by) 
{
    dt = as.data.table(.data)
    substitute(dt[, `:=`(...), by][]) %>% eval()
}

However, I could not use this function in other functions. For example:

t_f = function(dt,x){
  mutate_dt(dt,a = x)
}

t_f(iris,1)
#> Error in eval(jsub, SDenv, parent.frame()): object 'x' not found

Is there any way that I can make it work?

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
Hope
  • 109
  • 5

1 Answers1

3

You need to ensure that the expression is evaluated in the correct environment. R makes it easy by providing the convenience function eval.parent:

library(data.table)
mutate_dt = function (.data, ..., by) 
{
  dt = as.data.table(.data)
  eval.parent(substitute(dt[, `:=`(...), by][]))
}

mutate_dt(iris,a = 1)
#works

t_f = function(dt,x){
  mutate_dt(dt,a = x)
}

t_f(iris,2)
#works
Roland
  • 127,288
  • 10
  • 191
  • 288