Getting continent, mainland and island maps in R

Maps of continents, mainlands and islands can be useful, for example, for selecting areas — and then cropping or masking variables — for modelling a species’ distribution. Here’s a way to obtain such maps using the ‘geodata’ and ‘terra’ R packages:

# load required packages:

# import a world countries map:
countries <- world(resolution = 5, path = "maps")  # you may choose a smaller (more detailed) resolution for the polygon borders, and a different folder path to save the imported map

# import a table with country codes and continents:
cntry_codes <- country_codes()

# add this table to the countries map attributes:
head(cntry_codes[ , 1:4])
countries <- merge(countries, cntry_codes, by.x = "GID_0", by.y = "ISO3", all.x = TRUE)

# plot the countries map coloured according to "continent":
plot(countries, "continent", lwd = 0.2, main = "Countries by continent")

# dissolve (aggregate) countries into a continents map:
continents <- aggregate(countries, by = "continent")
plot(continents, "continent", lwd = 0.2)
# note that each continent (colour) is a multi-part polygon including mainland and islands - see also:
plot(continents[1, ])

# disaggregate continent polygons, to then separate islands and mainlands:
continents <- disagg(continents)

# get a map of just the continent mainlands (largest polygons):
largest <- (order(expanse(continents), decreasing = TRUE))[1:length(unique(continents$continent))]
mainlands <- continents[largest, ]
plot(mainlands, "continent", lwd = 0.2, main = "Continent mainlands")

# get a map of just the islands (i.e. polygons except mainlands):
islands <- erase(continents, mainlands)
plot(islands, "continent", lwd = 0.2, main = "World islands")
# you can then crop and mask a raster map to given islands or continents, e.g.:
elevation <- elevation_global(res = 10, path = "maps")  # you may choose a smaller (more detailed) resolution or pixel size
africa_mainland <- subset(mainlands, mainlands$continent == "Africa")
elev_afr_mainland <- crop(elevation, africa_mainland, mask = TRUE)
plot(elev_afr_mainland, main = "Elevation in mainland Africa")

You can also use the geodata::gadm() function to download polygons for particular countries (instead of the whole world), and then apply similar procedures to separate islands from mainlands.

1 thought on “Getting continent, mainland and island maps in R

  1. Pingback: Getting continent, mainland and island maps in R – Data Science Austria


Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s