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)`
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
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
*
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
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
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)以上是对数据库性数据的操作