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:
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)]
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),]