0

I have a raster rrepresenting values from 0 to 50 for the world. There are large areas with missing values NA values, including:

  • All oceans
  • Large inland regions such as deserts

The problem is that when I plot r all NAs appear with the same colour regardless of whether they are oceans or deserts. This does not look nice, so I want to display inland NAs in a different colour than oceans.

I was thinking perhaps I could grab a map representing continents (e.g. map("world")), and create a layer of all NAs in r that fall inside continents. Then, I can just overlap this new raster on top of r in a different colour.

How can I create a new raster with all the inland missing values in a raster?

1

As you haven't provided any datasets to start with I have made some reproducible ones:

Firstly, here is a random raster. Missing values are inserted fo 70% of the cells:

library(raster)
rast <- raster(ncol=100, nrow=100, xmn=-130, xmx=-70, ymn=0, ymx=60)
rast[] <- 1:(100*100)
rast[runif(100*100) >= 0.30] <- NA

Next, I will load the US boundaries from mapdata. I used the package sf to create the polygons, but sadly these are not compatible with rasters yet, so I converted it back to a spatial polygon at the end:

library(sf)
library(sp)
library(mapdata)
states <- sf::st_as_sf(map("state", plot = FALSE, fill = TRUE))
states <-  as(states, 'Spatial')

Comparing these two shapefiles:

plot(states)
plot(rast, add = TRUE)

enter image description here

The easiest way of locating cells over land is to use the mask function. This only leaves cells which overlay the polygon provided. Before doing the mask though, I will set all NAs to a specified value, in this case -9999.

# Replace all NAs with a value
rast[is.na(rast)] <- -9999

overlay <- mask(rast, states)

enter image description here

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.