I’m trying to solve the following problem.
I have a regular grid of points covering Europe
nx <- 361 ; ny <- 181
xmin <- -30.0 ; ymin <- 25.0
dx <- 0.25 ; dy <- 0.25
lat <- seq(ymin, ymin+(ny-1)*dy, dy)
lon <- seq(xmin, xmin+(nx-1)*dx, dx)
What I need doing is to associate the country to each grid cell and do country operations.
For example, I have to multiply the population density of France (Spain, Poland, etc) by a given factor.
I have produced an ugly script for masking the grid coordinates with country’s names, but it is not very practical and was wondering if there is a more efficient way to do it.
Here is the code I have produced :
m <- matrix(1, ncol=nx, nrow=ny) # create grid with unit (or whatever) value
n <- vector(mode='character', length=nx*ny) # empty character vector with same length as raster of grid
EUstates <- c('AUT', 'BEL', 'BGR', 'HRV', 'CYP', 'CZE', 'DNK', 'EST', 'FIN', 'FRA', 'DEU', 'GRC',
'HUN', 'IRL', 'ITA', 'LVA', 'LTU', 'LUX', 'MLT', 'NLD', 'POL', 'PRT', 'ROU', 'SVK',
'SVN', 'ESP', 'SWE', 'GBR')
r = raster( m, xmn=xmin,xmx=max(lon),ymn=ymin,ymx=max(lat)) # create a raster of grid 'm' to be used for masking
# now loop through EU countries for masking
for (c in EUstates){
EUc <- getData("GADM", country=c, level=0)
rr <- mask(r, EUc) # assigns NAN to whichever is outsided country c
n[which(!is.na(rr@data@values))] <- c # assign country name to cells that are not NAN
}
n[which(n=='')] <-'SEA' # all remaining empty cells assigned as 'SEA'