Canary

Differences between crop and mask in R

In this post we will try to explain the difference between two functions of the raster package that often lead to confusion.

Load R packages

library(tidyverse)
library(raster)
library(elevatr)

Obtain the data to work with. In this case we are going to focus on the Canary Islands.

shp <- getData("GADM", country = "ES", level = 4)
shp.can <- shp[shp@data$NAME_1 == "Islas Canarias", ]
elevation <- get_elev_raster(shp.can, z = 8)

Plotting Canary islands shapefile

plot(shp.can)

Plotting Digital Elevation Model


plot(elevation)
plot(shp.can, add=TRUE)

Now let’s see what we have come to see in this post.

Crop function

elev_crop <- crop(elevation, shp.can)
plot(elev_crop)

Mask function

elev_mask <- mask(elevation, shp.can)
plot(elev_mask)

However, it is very important to emphasise that when working with large rasters the mask function is not well implemented and often takes a long time. Therefore, I always recommend using the crop function before the mask function.

elev_crop <- mask(crop(elevation,
                       shp.can),
                  shp.can)

I hope this advice will help you and that you won’t spend hours staring at your computer screen waiting for the mask function to run….

Mario Mingarro López
PhD Student

Mario Mingarro.