我想同时将 dplyr::summarise
和 dplyr::summarise_each
应用于分组数据帧 . 可能吗?
我的数据如下:
mydf <- data.frame(
id = c(rep(1,2), rep(2, 3), rep(3, 4)),
amount = c(rep(1,4), rep(2,5)),
type1 = c(rep(1, 2), rep(0, 7)),
type2 = c(rep(0, 4), rep(1, 5))
)
mydf
# id amount type1 type2
#1 1 1 1 0
#2 1 1 1 0
#3 2 1 0 0
#4 2 1 0 0
#5 2 2 0 1
#6 3 2 0 1
#7 3 2 0 1
#8 3 2 0 1
#9 3 2 0 1
我想总结 id
amount
变量并得到 type
变量的最大值 . 我知道我可以这样做:
mydf %>%
group_by(id) %>%
summarise(amount = sum(amount), type1 = max(type1), type2 = max(type2))
但是,我有很多 type
变量,所以我更喜欢这样的东西(但总和也是 amount
) .
mydf %>%
group_by(id) %>%
summarise_each(funs(max), matches("type"))
3 回答
使用
dplyr
或者只是像@HongOoi所指出的那样
我不确定使用
dplyr
的惯用方法,但这是非常惯用的data.table
基本上,我们使用
c
组合两个操作,而lapply(.SD, max)
代表dplyr
中的mutate_each
而matches
只是grep
的包装(如清楚显示in the source code) .with = FALSE
用于data.table
或.SD
父框架(代表 S ub D ata)中列名的标准评估 .使用
dplyr
的更一般方法可能是:这样做的好处是只能将一个聚合函数应用于Veerendra Gadekar原始答案所拥有的每一列 . 如果我们需要
sd
或类似代替max
,它会派上用场,Hong Ooi的解决方案会在这种情况下破裂 . 如果有字符列,它也会中断 . 第三个优点是它丢弃了不属于计算的列 .另见my related question .