Importing and Visualizing World Bank Indicator Data in R

The World Bank aggregates a vast array of country-level data as indicators available from the World Bank Open Data portal. By joining that data with country polygons, you can create choropleth maps and perform geospatial analysis.

The World Bank Data Portal
  1. Search for an indicator of interest on data.worldbank.org. The variable used in this example is Fertilizer consumption (kilograms per hectare of arable land)
  2. Click the Download button, download a CSV file, and unzip it to your hard drive
  3. Review the CSV file in a spreadsheet program to find the latest year with adequate data for your purposes
  4. Note that the first four row of World Bank CSV files are metadata that can be skipped with the "skip=4" parameter. The year column names will have an X prepended to them (e.g. X2014) to avoid confusing the column names with numbers.
  5. Modify the script below to join your World Bank data to the country polygons and save to a new shapefile:
library(sf)

# Read the attributes into a data frame

attributes = read.csv("API_AG.CON.FERT.ZS_DS2_en_csv_v2_2164390.csv",
	skip=4, stringsAsFactors=F)

# Use country polygons from the maptools library

library(maptools) # For wrld_simpl polygons

data(wrld_simpl)

countries = st_as_sf(wrld_simpl)

# Join the attributes to the polygons

countries = merge(countries, attributes, by.x = "ISO3", by.y = "Country.Code")

# Convert the data column from text to numeric values

countries$Fertilizer.kg.hectare = suppressWarnings(as.double(countries$X2018))

# Keep only needed columns

countries = countries[,c("NAME", "ISO3", "Fertilizer.kg.hectare", "geometry")]

# Use a projection suitable for the world

robinson = "+proj=robin +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"

countries = st_transform(countries, robinson)

# Plot with a green color ramp

plot(countries["Fertilizer.kg.hectare"], breaks="quantile", 
	pal=colorRampPalette(c("#a0ffa0", "#004000")), key.pos=1,
	main="2018 Fertilizer Consumption by Country in kg per Hectare of Arable Land")
Output map (2021 FAO)