This is related to this question from Henrik Assign multiple columns using := in data.table, by group
But what if I want to create a new data.table with given column names instead of assigning new columns to an existing one?
f <- function(x){list(head(x,2),tail(x,2))}
dt <- data.table(group=sample(c('a','b'),10,replace = TRUE),val=1:10)
> dt
    group val
 1:     b   1
 2:     b   2
 3:     a   3
 4:     b   4
 5:     a   5
 6:     b   6
 7:     a   7
 8:     a   8
 9:     b   9
10:     b  10
I want to get a new data.table with predefined column names by calling the function f:
dt[,c('head','tail')=f(val),by=group]
I wish to get this:
   group head tail
1:     a    1    8
2:     a    3   10
3:     b    2    6
4:     b    5    9
But it gives me an error. What I can do is create the table then change the column names, but that seems cumbersome:
> dt2 <- dt[,f(val),by=group]
> dt2
   group V1 V2
1:     a  1  8
2:     a  3 10
3:     b  2  6
4:     b  5  9
> colnames(dt2)[-1] <- c('head','tail')
> dt2
   group head tail
1:     a    1    8
2:     a    3   10
3:     b    2    6
4:     b    5    9
Is it something I can do with one call?
 
     
    