Count number of rows within each group

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

    There are plenty of wonderful answers here already, but I wanted to throw in 1 more option for those wanting to add a new column to the original dataset that contains the number of times that row is repeated.

    df1$counts <- sapply(X = paste(df1$Year, df1$Month), 
                         FUN = function(x) { sum(paste(df1$Year, df1$Month) == x) })
    

    The same could be accomplished by combining any of the above answers with the merge() function.

提交回复
热议问题