Enhancing Tables with Flags Using the gt Package in R

The post explaining how to use the gt package in R to format tables with flags and other features, along with data manipulation using tidyverse and rvest
visualization
code
Statistics
Author
Affiliation
Published

September 6, 2024

Modified

September 8, 2024

Introduction

In this blog post, we’ll explore how to use the gt package in R to create visually appealing tables that include country flags and other enhancements. We’ll also cover data manipulation using tidyverse and rvest to prepare our data.

Step 1: Install and Load Required Packages

To get started, you’ll need several R packages: sf, tidyverse, rvest, gt, and gtsummary. Install and load these packages with the following commands:

require(sf)
require(tidyverse)
require(rvest)
require(gt)
require(gtsummary)

Step 2: Extract and Clean Data

We’ll extract population data from a Wikipedia page listing African countries by population. Using rvest, we can scrape this data into R:

africa = read_html("https://en.wikipedia.org/wiki/List_of_African_countries_by_population") |> 
  html_table()

We then select the first table from the list:

africa.pop = africa |> 
  purrr::pluck(1)

Step 3: Prepare Data for gt

Before we format our table, we need to clean and prepare our data. We’ll use janitor to clean column names and dplyr to select and join relevant columns:

codes = countrypops |> 
  distinct(country_name, .keep_all = T) |> 
  select(1:3)

africa.pop.code = africa.pop |> 
  janitor::clean_names() |> 
  rename(country_name = country) |> 
  select(country_name, pop = 4, growth_rate = 3) |> 
  left_join(codes) |> 
  filter(!country_name == "Total")

Step 4: Format Table with gt

Now we’re ready to create a table with flags using the gt package. First, we check available flag formatting options with:

gt::info_flags()

Complete List of Flag Icons Usable in gt

Flags like these can be used with the fmt_flag() function.

Entity Code
Andorra AD
United Arab Emirates AE
Afghanistan AF
Antigua and Barbuda AG
Albania AL
Armenia AM
Angola AO
Argentina AR
American Samoa AS
Austria AT
Australia AU
Aruba AW
Azerbaijan AZ
Bosnia and Herzegovina BA
Barbados BB
Bangladesh BD
Belgium BE
Burkina Faso BF
Bulgaria BG
Bahrain BH
Burundi BI
Benin BJ
Bermuda BM
Brunei Darussalam BN
Bolivia BO
Brazil BR
Bahamas BS
Bhutan BT
Botswana BW
Belarus BY
Belize BZ
Canada CA
Congo (Democratic Republic) CD
Central African Republic CF
Congo CG
Switzerland CH
Cote d'Ivoire CI
Chile CL
Cameroon CM
China CN
Colombia CO
Costa Rica CR
Cuba CU
Cabo Verde CV
Curacao CW
Cyprus CY
Czechia CZ
Germany DE
Djibouti DJ
Denmark DK
Dominica DM
Dominican Republic DO
Algeria DZ
Ecuador EC
Estonia EE
Egypt EG
Eritrea ER
Spain ES
Ethiopia ET
European Union EU
Finland FI
Fiji FJ
Micronesia (Federated States) FM
Faroe Islands FO
France FR
Gabon GA
United Kingdom GB
Grenada GD
Georgia GE
Ghana GH
Gibraltar GI
Greenland GL
Gambia, The GM
Guinea GN
Equatorial Guinea GQ
Greece GR
Guatemala GT
Guam GU
Guinea-Bissau GW
Guyana GY
Hong Kong HK
Honduras HN
Croatia HR
Haiti HT
Hungary HU
Indonesia ID
Ireland IE
Israel IL
Isle of Man IM
India IN
Iraq IQ
Iran (Islamic Republic) IR
Iceland IS
Italy IT
Jamaica JM
Jordan JO
Japan JP
Kenya KE
Kyrgyz Republic KG
Cambodia KH
Kiribati KI
Comoros KM
St. Kitts and Nevis KN
Korea, Dem. People's Rep. KP
Korea, Rep. KR
Kuwait KW
Cayman Islands KY
Kazakhstan KZ
Lao PDR LA
Lebanon LB
St. Lucia LC
Liechtenstein LI
Sri Lanka LK
Liberia LR
Lesotho LS
Lithuania LT
Luxembourg LU
Latvia LV
Libya LY
Morocco MA
Monaco MC
Moldova MD
Montenegro ME
St. Martin (French part) MF
Madagascar MG
Marshall Islands MH
North Macedonia MK
Mali ML
Myanmar MM
Mongolia MN
Macao MO
Northern Mariana Islands MP
Mauritania MR
Malta MT
Mauritius MU
Maldives MV
Malawi MW
Mexico MX
Malaysia MY
Mozambique MZ
Namibia NA
New Caledonia NC
Niger NE
Nigeria NG
Nicaragua NI
Netherlands NL
Norway NO
Nepal NP
Nauru NR
New Zealand NZ
Oman OM
Panama PA
Peru PE
French Polynesia PF
Papua New Guinea PG
Philippines PH
Pakistan PK
Poland PL
Puerto Rico PR
West Bank and Gaza PS
Portugal PT
Palau PW
Paraguay PY
Qatar QA
Romania RO
Serbia RS
Russian Federation RU
Rwanda RW
Saudi Arabia SA
Solomon Islands SB
Seychelles SC
Sudan SD
Sweden SE
Singapore SG
Slovenia SI
Slovak Republic SK
Sierra Leone SL
San Marino SM
Senegal SN
Somalia SO
Suriname SR
South Sudan SS
Sao Tome and Principe ST
El Salvador SV
Sint Maarten (Dutch part) SX
Syrian Arab Republic SY
Eswatini SZ
Turks and Caicos Islands TC
Chad TD
Togo TG
Thailand TH
Tajikistan TJ
Timor-Leste TL
Turkmenistan TM
Tunisia TN
Tonga TO
Turkiye TR
Trinidad and Tobago TT
Tuvalu TV
Tanzania TZ
Ukraine UA
Uganda UG
United States US
Uruguay UY
Uzbekistan UZ
St. Vincent and the Grenadines VC
Venezuela, RB VE
British Virgin Islands VG
Virgin Islands (U.S.) VI
Vietnam VN
Vanuatu VU
Samoa WS
Yemen YE
South Africa ZA
Zambia ZM
Zimbabwe ZW

To format our table with country flags, we use the fmt_flag() function. Here’s how to apply it:

africa.pop.code |> 
  select(country_code_2, country_name, pop, growth_rate) |> 
  gt() |> 
  fmt_flag(columns = country_code_2) |>
  cols_label(
    country_code_2 = "Flag",
    country_name = "Country",
    pop = "Population (2024)",
    growth_rate = "Growth rate"
  )
Flag Country Population (2024) Growth rate
Nigeria 227,882,945 15.4%
Ethiopia 128,691,692 8.7%
Egypt 114,535,772 7.7%
NA DR Congo 105,789,731 7.1%
Tanzania 66,617,606 4.5%
South Africa 63,212,384 4.3%
Kenya 55,339,003 3.7%
Sudan 50,042,791 3.4%
Uganda 48,656,601 3.3%
Algeria 46,164,219 3.1%
Morocco 37,712,505 2.5%
Angola 36,749,906 2.5%
Ghana 33,787,914 2.3%
Mozambique 33,635,160 2.3%
Madagascar 31,195,932 2.1%
NA Ivory Coast 31,165,654 2.1%
Cameroon 28,372,687 1.9%
Niger 26,159,867 1.9%
Mali 23,769,127 1.8%
Burkina Faso 23,025,776 1.6%
Malawi 21,104,482 1.4%
Zambia 20,723,965 1.4%
Chad 19,319,064 1.3%
Somalia 18,358,615 1.2%
Senegal 18,077,573 1.2%
Zimbabwe 16,340,822 1.1%
Guinea 14,405,465 1.0%
Benin 14,111,034 1.0%
Rwanda 13,954,471 1.0%
Burundi 13,689,450 0.9%
Tunisia 12,200,431 0.9%
South Sudan 11,483,374 0.8%
Togo 9,304,337 0.6%
Sierra Leone 8,460,512 0.6%
Libya 7,305,659 0.5%
NA Republic of the Congo 6,182,885 0.4%
Liberia 5,493,031 0.4%
Central African Republic 5,152,421 0.4%
Mauritania 5,022,441 0.3%
Eritrea 3,470,390 0.3%
Namibia 2,963,095 0.2%
NA Gambia 2,697,845 0.2%
Gabon 2,484,789 0.2%
Botswana 2,480,244 0.2%
Lesotho 2,311,472 0.2%
Guinea-Bissau 2,153,339 0.1%
Equatorial Guinea 1,847,549 0.1%
Mauritius 1,273,588 0.1%
Eswatini 1,230,506 0.1%
Djibouti 1,152,944 0.1%
Comoros 850,387 0.1%
NA Western Sahara 579,729 0.04%
NA Cape Verde 522,331 0.04%
NA São Tomé and Príncipe 230,871 0.02%
Seychelles 127,951 0.01%

Displaying national flags by region

To create a table displaying national flags by region, you first need to prepare and clean your data. Start by filtering the dataset to include only African countries. We use the spData package to access the world dataset, filter for Africa, and remove any geometry columns to focus on the tabular data. Next, we select relevant columns, including country codes, names, and regions.

afcon = spData::world |> 
  filter(continent == "Africa") |> 
  st_drop_geometry() |> 
  as_tibble() |> 
  select(country_code_2=1, country = name_long, region = subregion)

Once the data is prepared, join it with a dataset containing country codes. This dataset should map each country to its flag. Using dplyr, group the data by region and then summarize it to create a comma-separated list of country codes (representing flags) for each region. Rename this summarized column to “flag” for clarity.

afcon.tb = afcon |> 
  left_join(codes) |> 
  dplyr::group_by(region) |>
  dplyr::summarize(
    countries = paste0(country_code_2, collapse = ",")
  ) |> 
  rename(flag = countries)

Then, use the gt package to format and display the table. Create a table object with gt(), and then apply the fmt_flag() function to format the flag column so that it displays the flags associated with each country code. Label the columns appropriately using cols_label() to make the table more readable, with clear names like “Region” and “National Flags.”

afcon.tb |> 
  gt() |> 
  gt::fmt_flag(columns = flag) |>
  cols_label(
    region = "Region",
    flag = "Nationa Flags"
  )
Region Nationa Flags
Eastern Africa
Middle Africa
Northern Africa
Southern Africa
Western Africa

Conclusion

Using the gt package, we can enhance tables by including flags and applying various formatting options. This approach not only makes data more engaging but also improves readability. Experiment with different formatting functions to further customize your tables!

Citation

BibTeX citation:
@online{semba2024,
  author = {Semba, Masumbuko},
  title = {Enhancing {Tables} with {Flags} {Using} the `Gt` {Package} in
    {R}},
  date = {2024-09-06},
  url = {https://lugoga.github.io/kitaa/posts/summarytool/},
  langid = {en}
}
For attribution, please cite this work as:
Semba, M., 2024. Enhancing Tables with Flags Using the `gt` Package in R [WWW Document]. URL https://lugoga.github.io/kitaa/posts/summarytool/