Last active
February 12, 2021 01:45
-
-
Save MonkmanMH/c7cb5da451a5e2e60262f3f9a5caf43b to your computer and use it in GitHub Desktop.
dplyr's ungroup function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# {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