library(tidyverse)
library(gapminder)
library(gt)
library(gtExtras)Warning: package 'gtExtras' was built under R version 4.4.3
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.
library(tidyverse)
library(gapminder)
library(gt)
library(gtExtras)Warning: package 'gtExtras' was built under R version 4.4.3
This is your work area. Add as many code cells as you need.
# Filter for Americas & Europe in 1997
data_1997 <- gapminder %>%
filter(year == 1997, continent %in% c("Americas", "Europe"))
# Get two least populated countries per continent
least_populated <- data_1997 %>%
group_by(continent) %>%
arrange(pop) %>%
slice(1:2) %>%
ungroup()
# Create separate tables for population and life expectancy
pop_wide <- least_populated %>%
select(country, pop) %>%
pivot_wider(names_from = country, values_from = pop)
lifeExp_wide <- least_populated %>%
select(country, lifeExp) %>%
pivot_wider(names_from = country, values_from = lifeExp)
# Add a row identifier
pop_wide <- pop_wide %>% mutate(Metric = "Population")
lifeExp_wide <- lifeExp_wide %>% mutate(Metric = "Life Expectancy")
# Combine into final table
final_table <- bind_rows(pop_wide, lifeExp_wide) %>%
select(Metric, everything())
final_table <- final_table |>
gt() |>
tab_header(md("**Iceland \\
Fewer people, longer lives**")) |>
tab_spanner(label = md("**Americas**"), columns = c("Jamaica", "Trinidad and Tobago")) |>
tab_spanner(label = md("**Europe**"), columns = c("Iceland", "Montenegro")) |>
cols_label(Metric = fontawesome::fa("chart-bar"),Iceland = md("**Iceland**"), Montenegro = md("**Montenegro**"), Jamaica = md("**Jamaica**"), 'Trinidad and Tobago' = md("**Trinidad and Tobago**")) |>
tab_source_note(md("[Skál!](https://www.islandshotel.is/explore-iceland/blog/icelandic-phrases/)")) |>
gt_highlight_rows(columns = 4) |>
gt_theme_guardian()
final_table