Count number of rows within each group

后端 未结 14 2498
夕颜
夕颜 2020-11-21 05:01

I have a dataframe and I would like to count the number of rows within each group. I reguarly use the aggregate function to sum data as follows:



        
14条回答
  •  抹茶落季
    2020-11-21 05:29

    dplyr package does this with count/tally commands, or the n() function:

    First, some data:

    df <- data.frame(x = rep(1:6, rep(c(1, 2, 3), 2)), year = 1993:2004, month = c(1, 1:11))
    

    Now the count:

    library(dplyr)
    count(df, year, month)
    #piping
    df %>% count(year, month)
    

    We can also use a slightly longer version with piping and the n() function:

    df %>% 
      group_by(year, month) %>%
      summarise(number = n())
    

    or the tally function:

    df %>% 
      group_by(year, month) %>%
      tally()
    

提交回复
热议问题