Forgive me if I'm missing something... but isn't the standard list
syntax for data.table
what you're looking for? It is more concise and clearer IMHO.
x[,
list(s = sum(a),
p = prod(a)),
by=id]
# id s p
# 1: 1 25 945
# 2: 2 30 3840
You can also build up this list
as an expression
and eval
it.
foo <- expression(list(s=sum(a), p=prod(a)))
x[, eval(foo), by=id]
This can then be extended to a function (using as.quoted
from plyr
instead cause its handy):
expression_maker <- function(funs, cols, names) {
require(plyr)
list_contents <- paste0(names, '=', funs, '(', cols, ')', collapse=',')
as.quoted(paste('list(', list_contents, ')'))[[1]]
}
output <- expression_maker(funs=c('sum', 'prod'), cols=c('a', 'a'), names=c('s', 'p'))
x[, eval(output), by=id]
... But there be dragons!
per OP's edit:
x[,{s = sum(a); p=prod(a); y = sqrt(abs(s*p)); z = y+1; list(y, z)},by=id]
I would do this in a function and return a data.table
directly:
yourfun <- function(a) {
s <- sum(a)
p <- prod(a)
y <- sqrt(abs(s*p))
z <- y+1
data.table(y, z)
}
x[, yourfun(a), by=id]