I have raster data which resulted from calculations. The problem is that inside of the borders of the country some values are 0. Therefore there are NA values within the borders of the country and its shapefile as well as on the outside. Therefore when I change colors of the NA values both inside and outside of the border the color changes.
Map<- rgdal::readOGR("x")
Borders <- subset(Map, OBJECTID == "1")
myTheme <- RdBuTheme(cex= 0.6)
myTheme$panel.background$col = 'gray'
Rasterdata[is.na(Rasterdata)] <- 0
levelplot(Rasterdata, par.settings= myTheme) + latticeExtra::layer(sp.points(Borders, lwd = 1,5)
Does anyone know how to set the values outside of this Borders shapefile to NA again so I can change the colors correctly?
You can use rasterize
and cover
library(terra)
# raster data with NA's inside and outside the country
r <- rast(system.file("ex/elev.tif", package="terra"))
r[40:50,] <- NA
# borders of the country
v <- vect( system.file("ex/lux.shp", package="terra") )
# rasterize borders
x <- rasterize(v, r, 0)
# replace NA's inside country with zero
rr <- cover(r, x)
plot(rr)