library(tidyverse)
library(gapminder)
library(gt)
library(gtExtras)Assignment 5
As best you can, recreate this table showing the population and life expectancy for the two least populated countries in the Americas and Europe for 1997. Your assignment must show all code in the output. Use as many code chunks as you feel necessary, I recommend first getting the output to match the output below. Hint: you will probably find it easiest to use two pivot_wider() functions with a union() to replicate the data layout. Use the gapminder dataset.
The Grading Rubric is available at the end of this document.
The word Skál! should link to https://www.islandshotel.is/explore-iceland/blog/icelandic-phrases/ it doesn’t in the image because it is an image. The following packages are useful and loaded for you.
small_countries <- gapminder |>
filter(year == 1997, continent %in% c("Americas", "Europe")) |>
group_by(continent) |>
slice_min(pop, n = 2) |>
ungroup()
pop_row <- small_countries |>
select(country, value = pop) |>
mutate(value = as.double(round(value, 1))) |>
pivot_wider(names_from = country, values_from = value) |>
mutate(variable = "population")
lifeExp_row <- small_countries |>
select(country, value = lifeExp) |>
mutate(value = as.double(round(value, 1))) |>
pivot_wider(names_from = country, values_from = value) |>
mutate(variable = "life expectancy")
glimpse(small_countries)Rows: 4
Columns: 6
$ country <fct> "Trinidad and Tobago", "Jamaica", "Iceland", "Montenegro"
$ continent <fct> Americas, Americas, Europe, Europe
$ year <int> 1997, 1997, 1997, 1997
$ lifeExp <dbl> 69.465, 72.262, 78.950, 75.445
$ pop <int> 1138101, 2531311, 271192, 692651
$ gdpPercap <dbl> 8792.573, 7121.925, 28061.100, 6465.613
final_table <- union(pop_row, lifeExp_row) |>
select (variable, everything())
final_table2 <- final_table[, c(1, 3, 2, 4, 5)]
print(final_table2)# A tibble: 2 × 5
variable Jamaica `Trinidad and Tobago` Iceland Montenegro
<chr> <dbl> <dbl> <dbl> <dbl>
1 population 2531311 1138101 271192 692651
2 life expectancy 72.3 69.5 79 75.4
final_table2 |>
gt() |>
tab_header(md("🇮🇸Iceland
Fewer People, longer lives")) |>
cols_label(
variable = fontawesome::fa("chart-bar"),
Iceland = md("**Iceland**"),
Montenegro = md("**Montenegro**"),
Jamaica = md("**Jamaica**"),
'Trinidad and Tobago' = md("**Trinidad and
Tobago**")) |>
fmt_number(rows = 1,decimals = 0, use_seps = TRUE) |>
fmt_number(rows = 2,decimals = 1) |>
tab_spanner(label = md("**Americas**"),columns = 2:3) |>
tab_spanner(label = md("**Europe**"),columns = 4:5) |>
gt_highlight_cols(columns = 4) |>
gt_theme_guardian()