我想申请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
Run Code Online (Sandbox Code Playgroud)
我想总结过id的amount变量,并得到最大的type变量.我知道我可以这样做:
mydf %>%
group_by(id) %>%
summarise(amount = sum(amount), type1 = max(type1), type2 = max(type2))
Run Code Online (Sandbox Code Playgroud)
但是,我有很多type变量,所以我更喜欢这样的东西(但总和也是amount如此).
mydf %>%
group_by(id) %>%
summarise_each(funs(max), matches("type"))
Run Code Online (Sandbox Code Playgroud)
运用 dplyr
library(dplyr)
mydf %>%
group_by(id) %>%
mutate(amount = sum(amount)) %>%
mutate_each(funs(max), matches("type")) %>%
unique
#Source: local data table [3 x 4]
# id amount type1 type2
#1 1 2 1 0
#2 2 4 0 1
#3 3 8 0 1
Run Code Online (Sandbox Code Playgroud)
或者只是像@HongOoi所指出的那样
mydf %>%
group_by(id) %>%
mutate(amount=sum(amount)) %>%
summarise_each(funs(max))
Run Code Online (Sandbox Code Playgroud)
我不确定使用的惯用方法dplyr,但这是非常惯用的data.table
library(data.table)
setDT(mydf)[, c(amount = sum(amount),
lapply(.SD[, grep("type", names(mydf), value = TRUE), with = FALSE], max)),
by = id]
# id amount type1 type2
# 1: 1 2 1 0
# 2: 2 4 0 1
# 3: 3 8 0 1
Run Code Online (Sandbox Code Playgroud)
基本上,我们将两个操作组合使用c,而lapply(.SD, max)代表mutate_eachin dplyr并且matches只是一个包装器grep(如源代码中清楚显示的那样).with = FALSE用于标准评估一个data.table或.SD父框架内的列名称(代表S ub D ata).