Count number of rows within each group

后端 未结 14 2947
夕颜
夕颜 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:35

    If you want to include 0 counts for month-years that are missing in the data, you can use a little table magic.

    data.frame(with(df1, table(Year, Month)))
    

    For example, the toy data.frame in the question, df1, contains no observations of January 2014.

    df1
        x Year Month
    1   1 2012   Feb
    2   2 2014   Feb
    3   3 2013   Mar
    4   4 2012   Jan
    5   5 2014   Feb
    6   6 2014   Feb
    7   7 2012   Jan
    8   8 2014   Feb
    9   9 2013   Mar
    10 10 2013   Jan
    11 11 2013   Jan
    12 12 2012   Jan
    13 13 2014   Mar
    14 14 2012   Mar
    15 15 2013   Feb
    16 16 2014   Feb
    17 17 2014   Mar
    18 18 2012   Jan
    19 19 2013   Mar
    20 20 2012   Jan
    

    The base R aggregate function does not return an observation for January 2014.

    aggregate(x ~ Year + Month, data = df1, FUN = length)
      Year Month x
    1 2012   Feb 1
    2 2013   Feb 1
    3 2014   Feb 5
    4 2012   Jan 5
    5 2013   Jan 2
    6 2012   Mar 1
    7 2013   Mar 3
    8 2014   Mar 2
    

    If you would like an observation of this month-year with 0 as the count, then the above code will return a data.frame with counts for all month-year combinations:

    data.frame(with(df1, table(Year, Month)))
      Year Month Freq
    1 2012   Feb    1
    2 2013   Feb    1
    3 2014   Feb    5
    4 2012   Jan    5
    5 2013   Jan    2
    6 2014   Jan    0
    7 2012   Mar    1
    8 2013   Mar    3
    9 2014   Mar    2
    

提交回复
热议问题