I have a data with the states, month and year when people die. I need to calculate the median of the number of people died in each month (across years).
So, the first step is to calculate the number of people died by month and year:
data %>% group_by(state, month, year) %>% summarise(n = n())
data.frame(
stringsAsFactors = FALSE,
State = c("X", "X", "Y", "Y"),
Month = c(1L, 1L, 1L, 1L),
Year = c(2019L, 2020L, 2019L, 2020L),
n = c(20L, 15L, 45L, 54L)
)
at this point, I have a dataframe like this (these numbers are just an example):
| State | Month | Year | n |
|---|---|---|---|
| X | 1 | 2019 | 20 |
| X | 1 | 2020 | 15 |
| Y | 1 | 2019 | 45 |
| Y | 1 | 2020 | 54 |
But I want to calculate the median, so I write
data %>% group_by(state, month, year) %>% summarise(n = n()) %>% summarise(median = median(n))
| State | Month | median |
|---|---|---|
| X | 1 | 17.5 |
| Y | 1 | 49.5 |
I obtain my desired result, but i don't know if R is making some things from behind that I don't see.
My question is: It is something bad to 'summarise()' twice in a row?