How to use data.table inside a function?

data.table, r

Solution

This should be a better alternative to David's answer:

dynamicDT <- function(...) {
 dt[, eval(substitute(...))]
}

dynamicDT(z := x + y)
#   x y z
#1: 1 2 3

Problem

As a minimal working example, for instance, I want to be able to dynamically pass expressions to a data.table object to create new columns or modify existing ones: ``` dt <- data.table(x = 1, y = 2) dynamicDT <- function(...) { dt[, list(...)] } dynamicDT(z = x + y) ``` I was expecting: ``` z 1: 3 ``` but instead, I get the error: ``` Error in eval(expr, envir, enclos) : object 'x' not found ``` So how can I fix this? Attempts: I've seen this post, which suggests using `quote` or `substitute`, but ``` > dynamicDT(z = quote(x + y)) Error in `rownames<-`(`*tmp*`, value = paste(format(rn, right = TRUE), : length of 'dimnames' [1] not equal to array extent ``` or ``` > dynamicDT <- function(...) { + dt[, list(substitute(...))] + } > dynamicDT(z = x + y) Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, : first argument must be atomic ``` haven't worked for me.

Original source

Related problems