data.table:分组,然后与自定义函数聚合,返回几个新列

时间:2019-01-23 17:47:36

标签: r data.table grouping aggregate summary

在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

相关:

Assign multiple columns using := in data.table, by group

1 个答案:

答案 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