在data.table中,我该如何执行以下操作:
这里的技巧是生成多个新列,而不会多次调用聚合函数。
示例:
library(data.table)
mtcars_dt <- data.table(mtcars)
returnsOneColumn <- function(dt_group_all_columns){
"returned_value_1"
}
# works great, returns one new column as summary per group
mtcars_dt[,
list( new_column_1 = returnsOneColumn(dt_group_all_columns= .SD) ),
by = c("mpg", "cyl"),
.SDcols = colnames(mtcars_dt)
]
returnsMultipleColumns <- function (dt_group_all_columns){
list( "new_column_1" = "returned_value_1",
"new_column_2" = "returned_value_2" )
}
# does not work: Ideally, I would like to have mpg, cyl, and several columns
# generated from once calling returnsMultipleColumns
mtcars_dt[,
list( returnsMultipleColumns(dt_group_all_columns = .SD) ),
by = c("mpg", "cyl"),
.SDcols = colnames(mtcars_dt)
]
# desired output should look like this
#
# mpg cyl new_column_1 new_column_2
# 1: 21.0 6 returned_value_1 returned_value_2
# 2: 22.8 4 returned_value_1 returned_value_2
# 3: 21.4 6 returned_value_1 returned_value_2
# 4: 18.7 8 returned_value_1 returned_value_2
相关:
答案 0 :(得分:1)
您已经从该函数返回列表。您无需再次列出它们。因此,删除list
并使用下面的代码
mtcars_dt[,
returnsMultipleColumns(dt_group_all_columns = .SD),
by = c("mpg", "cyl"),
.SDcols = colnames(mtcars_dt)
]
mpg cyl new_column_1 new_column_2
1: 21.0 6 returned_value_1 returned_value_2
2: 22.8 4 returned_value_1 returned_value_2
3: 21.4 6 returned_value_1 returned_value_2
4: 18.7 8 returned_value_1 returned_value_2