--- title: "Comparison of life expenctancy for three countries" author: "your name" params: country_1: Belgium country_2: !r sample(c("United States", "Mexico", "Canada"), 1) --- ```{r load-packages} library(tidyverse) ``` ```{r load-data} gap <- read_csv("data/gapminder.csv") ``` Define a function, `plot_country`, that takes country names as one of its arguments and outputs a plot of life expectancy by year for each country and displays the GDP per capita of the country as size of the points. ```{r def-plot-country} plot_country <- function(gap, ctry) { ctry <- match.arg(ctry, unique(gap$country), several.ok = TRUE) gap %>% filter(country %in% ctry) %>% ggplot(aes(x = year, y = lifeExp, colour = country, size = gdpPercap)) + geom_point() + labs(title = paste(ctry, collapse = ", "), subtitle = "Change in life expectancy and GDP per capita") } country_3 <- "South Africa" ``` We compare the change in life expectancy for `r params$country_1`, `r params$country_2` and `r country_3`: ```{r plot-country, echo=FALSE} plot_country(gap, c(params$country_1, params$country_2, country_3)) ``` ```{r table-country} gap %>% filter(country %in% c(params$country_1, params$country_2, country_3)) %>% select(country, lifeExp, pop, gdpPercap) %>% group_by(country) %>% summarise_all(mean) %>% knitr::kable() ``` A few new things are happening in this document: - The use of parameters to change things in only 1 place - The use of R functions within parameters with the `!r` notation - The use of functions to generate plots, making it easier to do: - type checking - reduce code repetition - The use of `knitr::kable` to generate nicely formatted (simple) tables within Rmarkdown documents