Count number of rows within each group

后端 未结 14 2503
夕颜
夕颜 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 old question without a data.table solution. So here goes...

    Using .N

    library(data.table)
    DT <- data.table(df)
    DT[, .N, by = list(year, month)]
    
    0 讨论(0)
  • 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),]
    
    0 讨论(0)
提交回复
热议问题