dplyr包之汇总: summarise()

Description

Summarise multiple values to a single value.

汇总多个值到一个值。

 summarise(mtcars, mean(disp))
  mean(disp)
1   230.7219

不分组直接求一列的平均值

 summarise(group_by(mtcars, cyl), mean(disp))
# A tibble: 3 × 2
    cyl `mean(disp)`
  <dbl>        <dbl>
1     4     105.1364
2     6     183.3143
3     8     353.1000

根据cyl分组求平均,指明数据集后队列的访问数据集的名字不用再写

 summarise(group_by(mtcars, cyl), m = mean(disp), sd = sd(disp))
# A tibble: 3 × 3
    cyl        m       sd
  <dbl>    <dbl>    <dbl>
1     4 105.1364 26.87159
2     6 183.3143 41.56246
3     8 353.1000 67.77132

多种汇总方式

# With data frames, you can create and immediately use summaries
当你的原始数据集是数据框你可以直接使用

 by_cyl <- mtcars %>% group_by(cyl)

 by_cyl
Source: local data frame [32 x 11]
Groups: cyl [3]
     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
*  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1   21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4
2   21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4
3   22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1
4   21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1
5   18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2
6   18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1
7   14.3     8 360.0   245  3.21 3.570 15.84     0     0     3     4
8   24.4     4 146.7    62  3.69 3.190 20.00     1     0     4     2
9   22.8     4 140.8    95  3.92 3.150 22.90     1     0     4     2
10  19.2     6 167.6   123  3.92 3.440 18.30     1     0     4     4
# ... with 22 more rows

typeof( by_cyl)
[1] "list"

将数据集传递给group_by之后通过cyl列分组之后的数据是一个list


by_cyl %>% summarise(a = n(), b = a + 1)

# A tibble: 3 × 3
    cyl     a     b
  <dbl> <int> <dbl>
1     4    11    12
2     6     7     8
3     8    14    15

对分组后的数据进行汇总求行数

summarise(group_by(mtcars, cyl), a= n(), b = a+1)
# A tibble: 3 × 3
    cyl     a     b
  <dbl> <int> <dbl>
1     4    11    12
2     6     7     8
3     8    14    15

的结果与分步执行之后的结果一样

## Not run: 
如果不是可以通过下面这种方式
# You can't with data tables or databases
你不能直接使用数据表或者数据集
by_cyl_dt <- mtcars %>% dtplyr::tbl_dt() %>% group_by(cyl)
先转化微数据框形式之后分组
by_cyl_dt %>% summarise(a = n(), b = a + 1)
对分组之后的结果汇总
by_cyl_db <- src_sqlite(":memory:", create = TRUE) %>%
  copy_to(mtcars) %>% group_by(cyl)
by_cyl_db %>% summarise(a = n(), b = a + 1)
以上是对数据库性数据的操作


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值