2

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.

1
  • Can you show your code that used "intersect" and "over"? It might have been very close to working and it gives us a starting point. Try and show code and plots whenever possible, and also summaries of your data (the output of summary(things) is usually a good start). This helps us help you!
    – Spacedman
    May 14 '20 at 18:43
0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.