Skip to content

Instantly share code, notes, and snippets.

@MonkmanMH
Last active February 12, 2021 01:45
Show Gist options
  • Save MonkmanMH/c7cb5da451a5e2e60262f3f9a5caf43b to your computer and use it in GitHub Desktop.
Save MonkmanMH/c7cb5da451a5e2e60262f3f9a5caf43b to your computer and use it in GitHub Desktop.
dplyr's ungroup function
# {dplyr}'s `ungroup()` function
```{r}
# packages
library(gapminder)
library(dplyr)
```
In this example, we calculate the difference in a country's life expectancy from the continent's mean life expectancy
- for example, the difference between life expectancy in Canada and the mean life expectancy of countries in the Americas
Step 1:
* Filter for 2007
* Then group by continent and
* Mutate to get the mean continental life expectancy
```{r}
gapminder %>%
filter(year == 2007) %>%
group_by(continent) %>%
mutate(lifeExp_mean = mean(lifeExp))
```
By adding the `ungroup()` function, we revert to the country-level data frame but now with the continent mean as a variable
And then we can append another mutate to calculate the difference
```{r}
gapminder %>%
filter(year == 2007) %>%
group_by(continent) %>%
mutate(lifeExp_mean = mean(lifeExp)) %>%
#
ungroup() %>%
mutate(lifeExp_diff = lifeExp - lifeExp_mean)
```
-30-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment