在一个链中使用dplyr的多个聚合(分类和数字)

Lyz*_*deR 6 r dplyr

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

我有这样的数据集:

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")
Run Code Online (Sandbox Code Playgroud)

这显示如下:

        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
Run Code Online (Sandbox Code Playgroud)

我的目标是计算每天最常见的颜色,形状和平均值.我的预期输出如下:

        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
Run Code Online (Sandbox Code Playgroud)

我最终使用split并编写自己的函数来计算上面的a data.frame,然后用于snow::clusterApply并行运行它.它足够有效(我的原始数据集长约10M行),但我想知道这是否可以在一个链中使用dplyr.效率对此非常重要,因此能够在一个链条中运行它非常重要.

Dav*_*son 9

你可以做到

dat %>% group_by(date) %>%
    summarize(colour = names(which.max(table(colour))),
              shape = names(which.max(table(shape))),
              value = mean(value))
Run Code Online (Sandbox Code Playgroud)