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:
Considering @Ben answer, R would throw an error if df1
does not contain x
column. But it can be solved elegantly with paste
:
aggregate(paste(Year, Month) ~ Year + Month, data = df1, FUN = NROW)
Similarly, it can be generalized if more than two variables are used in grouping:
aggregate(paste(Year, Month, Day) ~ Year + Month + Day, data = df1, FUN = NROW)