一个链中带有 dplyr 的多个聚合(分类和数字)

Multiple aggregations (categorical and numeric) with dplyr in one chain

我今天遇到了一个问题,想找出一种在 dplyr 中进行聚合的方法,但由于某种原因无法提出解决方案(尽管我认为这应该很容易)。

我有这样的数据集:

structure(list(date = structure(c(16431, 16431, 16431, 16432, 
16432, 16432, 16433, 16433, 16433), class = "Date"), colour = structure(c(3L, 
1L, 1L, 2L, 2L, 3L, 3L, 1L, 1L), .Label = c("blue", "green", 
"red"), class = "factor"), shape = structure(c(2L, 2L, 3L, 3L, 
3L, 2L, 1L, 1L, 1L), .Label = c("circle", "square", "triangle"
), class = "factor"), value = c(100, 130, 100, 180, 125, 190, 
120, 100, 140)), .Names = c("date", "colour", "shape", "value"
), row.names = c(NA, -9L), class = "data.frame")

显示如下:

        date colour    shape value
1 2014-12-27    red   square   100
2 2014-12-27   blue   square   130
3 2014-12-27   blue triangle   100
4 2014-12-28  green triangle   180
5 2014-12-28  green triangle   125
6 2014-12-28    red   square   190
7 2014-12-29    red   circle   120
8 2014-12-29   blue   circle   100
9 2014-12-29   blue   circle   140

我的目标是计算每天出现频率最高的颜色、形状和平均值。我的预期输出如下:

        date colour    shape value
1 27/12/2014   blue   square   110
2 28/12/2014  green triangle   165
3 29/12/2014   blue   circle   120

我最终使用 split 并编写了自己的函数来为 data.frame 计算上述内容,然后并行使用 snow::clusterApply 到 运行。它足够高效(我的原始数据集长约 1000 万行)但我想知道这是否会在使用 dplyrone chain 中发生。效率对此非常重要,因此能够 运行 它在一条链中非常重要。

你可以

dat %>% group_by(date) %>%
    summarize(colour = names(which.max(table(colour))),
              shape = names(which.max(table(shape))),
              value = mean(value))