Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
group_by solutions
# group_by
`summarize` becomes truly powerful when paired with `group_by`, which enables us to perform calculations on each group.
Calculate the mean hours of sleep for females and males using `group_by` and `summarize`.
nhanes %>%
group_by(gender) %>%
summarize(mean_hours_sleep = mean(sleep_hrs_night, na.rm = TRUE))
We can use `group_by` with multiple groups.
Use `group_by` for `gender` and `work` (whether or not respondents are working) before calculating mean hours of sleep.
nhanes %>%
group_by(gender, work) %>%
summarize(mean_hours_sleep = mean(sleep_hrs_night, na.rm = TRUE),
number_of_observations = n())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment