我想在一个分组的数据框中同时应用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
变量求和并取得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"))
dplyr
解决方案。 - David Arenburgdplyr
可能不允许这样做。那么我应该寻找一个非dplyr
的解决方案。 - janosdivenyiunique(mydf %>% group_by(id) %>% mutate(amount = sum(amount)) %>% mutate_each(funs(max), matches("type")))
? - Veerendra Gadekarmydf%>%按id分组%>% mutate(amount = sum(amount))%>% mutate_each(funs(max),matches(“type”))%>% unique
- Carlos Cinelli