Question
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:
df2 <- aggregate(x ~ Year + Month, data = df1, sum)
Now, I would like to count observations but can't seem to find the proper
argument for FUN
. Intuitively, I thought it would be as follows:
df2 <- aggregate(x ~ Year + Month, data = df1, count)
But, no such luck.
Any ideas?
Some toy data:
set.seed(2)
df1 <- data.frame(x = 1:20,
Year = sample(2012:2014, 20, replace = TRUE),
Month = sample(month.abb[1:3], 20, replace = TRUE))
Answer
The tidyverse/dplyr way:
library(dplyr)
df1 %>% count(Year, Month)