r - naming a list when returning values from data.table -
when returning items data.table
, nice if automatically took on names of variables. how 1 this? mean:
require(data.table) x = data.table(a=1:10, id=1:2) x[,{s = sum(a); p=prod(a); y = sqrt(abs(s*p)); z = y+1; list(y, z)},by=id] # id v1 v2 #1: 1 25 945 #2: 2 30 3840
instead of v1
, v2
nice if columsn labeled s
, p
. it's no big thing here if have 20 columns becomes real pain. ideas on how this?
edit: changed question make clear why don't list(name = value)
forgive me if i'm missing something... isn't standard list
syntax data.table
you're looking for? more concise , 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 build list
expression
, eval
it.
foo <- expression(list(s=sum(a), p=prod(a))) x[, eval(foo), by=id]
this can extended function (using as.quoted
plyr
instead cause 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]
... there 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 in function , return 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]
Comments
Post a Comment