TransWikia.com

How do I get the country codes from polygons in my "grid data" polygon dataframe?

Geographic Information Systems Asked on November 29, 2021

I am relatively new to working with spatial data in R.
I have two spatial polygon data frames.
The first one is a shapefile which has a grid structure of a resolution of 0.5*0.5 for the whole world.
The second one is a shapefile which has the boundaries for Africa as the polygons including the state names .
Both have latitude-longitude coordinates.

I would like to overlay the two files and drop every cell that is not in the Africa file, thus I would like to have only the cells that belong to Africa.
In a second step I would then like to assign each grid cell the country it belongs to.
Does anyone have an idea how I would do that?
intersect() or over() didn’t work for me.

One Answer

I've done this in the past with a little bit of jiggery-pokery.

So the PRIO-GRID structure can be matched with country codes, but you have to download them first from their website. I saved them as priogrid.csv in the code below.

In addition, they use a coding scheme no one uses except for the incidental political scientist. Hence they need to be matched with a more common coding scheme like ISO. For this I used the cshapes and countrycode package.

Here's my shot at this: maybe not the cleanest way but it works (for what I need though). I am sure there might be some directer way to match the cells with the country codes but I haven't found out how yet. I guess you can adapt it to suit your needs. Specifically matching it with your shape file for national boundaries.

#libraries
library(countrycode)
library(data.table)
library(rgdal)
library(cshapes)

#get GW code for African countries
poly <- cshp(date=as.Date("2014-12-31"), useGW=TRUE) #load map
poly$continent <- countrycode(poly$ISONAME,
                              "country.name", "continent", warn = TRUE) 
gw <- as.vector(na.omit(poly$GWCODE[poly$continent == "Africa"])) #GW country code

#get GID for African countries
gid.gw <- fread("priogrid.csv") #NB: this needs to be downloaded
gid <- gid.gw$gid[gid.gw$gwno %in% gw]

#subset priogrid to cells in Africa
grid <- readOGR(dsn = "priogrid_cellshp", layer = "priogrid_cell")
grid <- grid[grid$gid %in% gid,]

#add country code
intermediate <- data.table(gwno = poly$GWCODE, iso = poly$ISO1AL3)
gid.gw <- merge(gid.gw, intermediate, all.x=TRUE)
grid <- merge(grid, gid.gw, all.x = TRUE)

Answered by horseoftheyear on November 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP