1
votes

I have a very large rasterbrick and some coordinates held in a different object. I wish to use the points as a mask, returning NA for all cells except where my points are located (for my particular application I need to preserve the extent, resolution and origin of the input rasterbrick).

I can accomplish this with the following:

library(raster)
library(tidyverse)
library(sf)

# Load a rasterbrick
b <- brick(system.file("external/rlogo.grd", package="raster"))

# Create some random points as test points for masking
pts<-as_tibble(rasterToPoints(b[[1]])) %>% 
  select(x, y) %>% 
  sample_n(15, replace = TRUE)

plot(b[[1]])
points(pts)

# Convert points to SpatialPoints so they can be passed to `mask`
pts <- st_as_sf(x = pts, coords = c("x", "y"),
                crs = crs(b))

# Mask stack using pts
xx<-raster::mask(b, pts)
plot(xx)

In this example, the code executes very quickly but when scaling this up, it can take a long time to run. What would be a more efficient way of doing this for a large, multi-layer rasterbrick? For a sense of scale, my rasterbrick's are360, 720, 259200, 3653 (nrow, ncol, ncell, nlayers)` so it would be great to speed things along.

1

1 Answers

1
votes

That is a lot of layers.

Your code (with some simplification)

library(raster)
b <- brick(system.file("external/rlogo.grd", package="raster"))
set.seed(1)
pts <- sampleRandom(b, 10, sp=TRUE)
xx <- raster::mask(b, pts)

Two alternatives, I do not know if they are faster.

Alternative 1

y <- rasterize(pts, b, 1)
m <- mask(b, y)

Alternative 2

v <- extract(b, pts)
r <- rasterize(pts, b, v)