Count number of rows within each group

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

    Considering @Ben answer, R would throw an error if df1 does not contain x column. But it can be solved elegantly with paste:

    aggregate(paste(Year, Month) ~ Year + Month, data = df1, FUN = NROW)
    

    Similarly, it can be generalized if more than two variables are used in grouping:

    aggregate(paste(Year, Month, Day) ~ Year + Month + Day, data = df1, FUN = NROW)
    

提交回复
热议问题