Count number of rows by group using dplyr

前端 未结 4 988
难免孤独
难免孤独 2020-11-27 14:56

I am using the mtcars dataset. I want to find the number of records for a particular combination of data. Something very similar to the count(*) gr

相关标签:
4条回答
  • 2020-11-27 15:37

    There's a special function n() in dplyr to count rows (potentially within groups):

    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
    

    But dplyr also offers a handy count function which does exactly the same with less typing:

    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
    
    0 讨论(0)
  • 2020-11-27 15:38

    another approach is to use the double colons:

    mtcars %>% 
      dplyr::group_by(cyl, gear) %>%
      dplyr::summarise(length(gear))
    
    0 讨论(0)
  • 2020-11-27 15:40

    I think what you are looking for is as follows.

    cars_by_cylinders_gears <- mtcars %>%
      group_by(cyl, gear) %>%
      summarise(count = n())
    

    This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.

    0 讨论(0)
  • Another option, not necesarily more elegant, but does not require to refer to a specific column:

    mtcars %>% 
      group_by(cyl, gear) %>%
      do(data.frame(nrow=nrow(.)))
    
    0 讨论(0)
提交回复
热议问题