Count number of rows within each group

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

    An alternative to the aggregate() function in this case would be table() with as.data.frame(), which would also indicate which combinations of Year and Month are associated with zero occurrences

    df<-data.frame(x=rep(1:6,rep(c(1,2,3),2)),year=1993:2004,month=c(1,1:11))
    
    myAns<-as.data.frame(table(df[,c("year","month")]))
    

    And without the zero-occurring combinations

    myAns[which(myAns$Freq>0),]
    

提交回复
热议问题