I have a problem including a data.table
operation in a function. Input arguments are the data.table name and the column/variable name.
I can refer to the data.table by using the get()
command. However, using the same command for the variable name doesn't work out. I know that get()
might not be appropriate in case of the column/variable name, but I am stuck with which command to use.
EDITED: I have now included substitute()
instead of get()
and it still doesn't work.
toy_example_fun <- function(d, .expr){
.expr = substitute(.expr)
setkey(get(d), .expr) # ==> doesn't work
d.agg <- get(d)[,list(sum(y), sum(v)), by=.expr] # --> works
}
toy_example_fun("DT", x)
ALTERNATIVE: quote()
--> This works. However, I am interested in a solution that works inside a function.
DT <- data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)
d <- "DT"
variable <- quote(x)
d.agg <- get(d)[,list(sum(y), sum(v)), by=variable]
Even though, the latter alternative works variable <- quote(x)
produces an error message:
<simpleError in doTryCatch(return(expr), name, parentenv, handler): object 'x' not found>
<simpleError in is.scalar(val): object 'x' not found>
<simpleError in is.data.frame(obj): object 'x' not found>
Thanks for your help.