一起使用dplyr的总结和总结_ [英] Use dplyr's summarise and summarise_each together?

查看:116
本文介绍了一起使用dplyr的总结和总结_的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时应用 dplyr ::总结 dplyr :: summarise_each 数据框。可以吗?

I would like to apply dplyr::summarise and dplyr::summarise_each at the same time for a grouped data frame. Is it possible?

我的资料如下所示:

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 金额变量,并获得最大值类型变量。我知道我可以这样做:

I would like to sum over id the amount variable and get the max for the type variables. I know I can do this as follows:

mydf %>% 
    group_by(id) %>% 
    summarise(amount = sum(amount), type1 = max(type1), type2 = max(type2))

但是,我有很多类型变量,所以我更喜欢这样的东西(但是总和 amount

However, I have a lot of type variables so I would prefer something like this (but with the sum of amount as well).

mydf %>%
    group_by(id) %>%
    summarise_each(funs(max), matches("type"))


推荐答案

使用 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

或简单地说<@> @HongOoi表示

mydf %>% 
     group_by(id) %>% 
     mutate(amount=sum(amount)) %>% 
     summarise_each(funs(max))

这篇关于一起使用dplyr的总结和总结_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆