dplyr包之分组动作 group_by()

Description

Most data operations are useful done on groups defined by variables in the the dataset. The group_by function takes an existing tbl and converts it into a grouped tbl where operations are performed "by group".

通过数据集中的变量构造分组是非常有用的。group_by函数接受现有的资源并将其转换为一个分组


group_by接受一下集中数据类型

  • data.frame: grouped_df

  • data.table: grouped_dt

  • SQLite: src_sqlite

  • PostgreSQL: src_postgres

  • MySQL: src_mysql

使用方法

by_cyl <- group_by(mtcars, cyl)
summarise(by_cyl, mean(disp), mean(hp))
filter(by_cyl, disp == max(disp))
filter(by_cyl, disp == max(disp))
Source: local data frame [3 x 11]
Groups: cyl [3]


    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
 
1  21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1
2  24.4     4 146.7    62  3.69 3.190 20.00     1     0     4     2
3  10.4     8 472.0   205  2.93 5.250 17.98     0     0     3     4

返回每组中最大的disp的数据

> by_vs_am <- group_by(mtcars, vs, am)
> by_vs <- summarise(by_vs_am, n = n())
> by_vs
Source: local data frame [4 x 3]
Groups: vs [?]


     vs    am     n
 
1     0     0    12
2     0     1     6
3     1     0     7
4     1     1     7
> summarise(by_vs, n = sum(n))
# A tibble: 2 × 2
     vs     n
 
1     0    18
2     1    14

至合并了一个分组

summarise(ungroup(by_vs), n = sum(n))
# A tibble: 1 × 1
      n
 
1    32

把所有的分组数据擦除

 group_by(mtcars, vsam = vs + am)
Source: local data frame [32 x 12]
Groups: vsam [3]


     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb  vsam
   
1   21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4     1
2   21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4     1
3   22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1     2
4   21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1     1
5   18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2     0
6   18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1     1

对两个变量的和进行分类

group_by(mtcars, vs2 = vs)
Source: local data frame [32 x 12]
Groups: vs2 [2]


     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb   vs2
   
1   21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4     0
2   21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4     0
3   22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1     1
4   21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1     1
5   18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2     0
6   18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1     1

只对一个变量分组

groups(group_by(by_cyl, vs, am))
[[1]]
vs
[[2]]
am
查看分组数目

> groups(group_by(by_cyl, vs, am, add = TRUE))
[[1]]
cyl
[[2]]
vs
[[3]]
am
对分组后的数据在分组并将之间的分组也计算进来

 groups(group_by(by_cyl, cyl, cyl))
[[1]]
cyl

重复的分组会舍弃


你可能感兴趣的:(R,dplyr包)