-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcm_007.Rmd
84 lines (56 loc) · 2.05 KB
/
cm_007.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
---
title: "cm007 Exercises: Practice with `dplyr`"
output:
html_document:
keep_md: true
theme: paper
---
<!---The following chunk allows errors when knitting--->
```{r allow errors, echo = FALSE}
knitr::opts_chunk$set(error = TRUE, warning = FALSE)
```
```{r}
suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(gapminder))
suppressPackageStartupMessages(library(tsibble))
```
This worksheet contains exercises aimed for practice with `dplyr`.
1. (a) What's the minimum life expectancy for each continent and each year? (b) Add the corresponding country to the tibble, too. (c) Arrange by min life expectancy.
```{r}
gapminder %>%
group_by(continent,year) %>%
summarize(min_life = min(lifeExp),
country= country[lifeExp==min_life]) %>%
arrange (min_life)
##arrange to minimum life Exp. , dplyr creates column on the fly
```
2. Calculate the growth in population since the first year on record _for each country_ by rearranging the following lines, and filling in the `FILL_THIS_IN`. Here's another convenience function for you: `dplyr::first()`.
```
mutate(rel_growth = FILL_THIS_IN) %>%
arrange(FILL_THIS_IN) %>%
gapminder %>%
DT::datatable()
group_by(country) %>%
```
```{r}
gapminder %>%
group_by(country) %>%
arrange(year) %>%
mutate(rel_growth = pop-first(pop)) %>%
DT::datatable()
```
3. Determine the country that experienced the sharpest 5-year drop in life expectancy, in each continent, sorted by the drop, by rearranging the following lines of code. Ensure there are no `NA`'s. Instead of using `lag()`, use the convenience function provided by the `tsibble` package, `tsibble::difference()`:
```
```
```{r}
gapminder %>%
group_by(country) %>%
arrange(year) %>%
mutate(inc_life_exp = difference(lifeExp)) %>%
drop_na() %>%
ungroup() %>%
group_by(continent) %>%
filter(inc_life_exp == min(inc_life_exp)) %>% ## Filtering happens independantly within each group
arrange(inc_life_exp) %>% ## Arrange works independantly of groups
knitr::kable()
```