Count number of rows within each group

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

    Create a new variable Count with a value of 1 for each row:

    df1["Count"] <-1
    

    Then aggregate dataframe, summing by the Count column:

    df2 <- aggregate(df1[c("Count")], by=list(Year=df1$Year, Month=df1$Month), FUN=sum, na.rm=TRUE)
    

提交回复
热议问题