使用dplyr/group_by查找行数

cha*_*mee 66 r plyr dplyr

我正在使用mtcars数据集.我想找到特定数据组合的记录数.与count(*)SQL中的group by子句非常相似的东西.ddply()来自plyr正在为我工​​作

library(plyr)
ddply(mtcars, .(cyl,gear),nrow)
Run Code Online (Sandbox Code Playgroud)

有输出

  cyl gear V1
1   4    3  1
2   4    4  8
3   4    5  2
4   6    3  2
5   6    4  4
6   6    5  1
7   8    3 12
8   8    5  2
Run Code Online (Sandbox Code Playgroud)

使用此代码

library(dplyr)
g <- group_by(mtcars, cyl, gear)
summarise(g, length(gear))
Run Code Online (Sandbox Code Playgroud)

有输出

  length(cyl)
1          32
Run Code Online (Sandbox Code Playgroud)

我找到了传入的各种功能,summarise()但似乎没有一个对我有用.我发现的一个功能是sum(G)返回

Error in eval(expr, envir, enclos) : object 'G' not found
Run Code Online (Sandbox Code Playgroud)

尝试使用n(),返回

Error in n() : This function should not be called directly
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我怎样才能获得group_by()/ summarise()为我工作?

tal*_*lat 104

n()dplyr中有一个特殊的函数来计算行数(可能在组内):

library(dplyr)
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(n = n())
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2
Run Code Online (Sandbox Code Playgroud)

但是dplyr还提供了一个方便的count功能,它可以用更少的输入完成相同的操作:

count(mtcars, cyl, gear)          # or mtcars %>% count(cyl, gear)
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2
Run Code Online (Sandbox Code Playgroud)


小智 14

另一种方法是使用双冒号:

mtcars %>% 
  dplyr::group_by(cyl, gear) %>%
  dplyr::summarise(length(gear))
Run Code Online (Sandbox Code Playgroud)


tb.*_*tb. 12

我认为您正在寻找的内容如下。

cars_by_cylinders_gears <- mtcars %>%
  group_by(cyl, gear) %>%
  summarise(count = n())
Run Code Online (Sandbox Code Playgroud)

这是使用 dplyr 包。这本质上是 docendo discimus 提供的 count() 解决方案的简写版本。