I want to produce one PNG image for each country in the world. The pixel colors come from a raster
that describes the vegetation, and the boundaries of the countries come from a shapefile
.
I managed to do almost all of it using the raster
and rgdal
libraries in R:
library(raster)
r <- raster('gm_lc_v3.tif')
library(rgdal)
p <- readOGR('ne_10m_admin_0_countries','ne_10m_admin_0_countries')
i <- 66 # Dominican Republic, a small country for fast example
country <- crop(r,p[i,]) # produces the rectangular crop below
plot(country)
m1 <- mask(country,p[i,]) # crops on the country boundary
plot(m1)
m2 <- mask(country,p[i,],inverse=T) # crops outside the boundary
m2[m2 < 20] <- NA # turns all land into NA
What I need now is to combine the two rasters (m1 and m2) into a single raster, with all data from the country, and only land/water data from outside the country. Like this (made in Gimp):
I have tried all the following so far, but without success:
m3 <- cover(m1,m2)
m3 <- cover(m1,m2,identity=T)
m3 <- merge(m1,m2)
m3 <- overlay(m1,m2,fun=function(x,y){return(x+y)})
m3 <- mask(m1,m2)
m3 <- stack(m2,m1)
They return all black, or different colors from the original. What am I missing?