Is correct summarizing 2 times in a row in R?

Viewed 87

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?

1 Answers

After the first summarise, by default the last grouping is dropped i.e. year. So, the second summarise is based on the 'State' and 'Month' (if that it is the OP's desired outcome). In this case, two summarise makes sense. It may be better to specify the .groups option to make sure that what we need i.e. drop_last will drop the last group and in the second summarise, remove the grouping with drop

library(dplyr)
data %>% 
  group_by(state, month, year) %>%
  summarise(n = n(), .groups = 'drop_last') %>%
  summarise(median = median(n), .groups = 'drop')
Related