2
votes

I am trying to extract two regions ex1 and ex2 (in exlist) from a list of rasters (rasterlist) using the apply family and extract from the raster package. I could use a nested for loop but was wondering if there is a way to achieve this in with one of the apply family members, since nested for loops are considered more or less bad practice in R. Here the dummy code:

library(raster)
ras1 <- raster(matrix(runif(20), nrow = 5, ncol = 5))
ras2 <- ras1 * 2
ras3 <- ras1 * 0.5
rasterlist <- list(ras1, ras2, ras3)
ex1 <- extent(0, 0.4, 0, 0.4)
ex2 <- extent(0.6, 1, 0.4, 1)
exlist <- list(ex1, ex2)

At the moment I've got this as a (rather unsatisfying) solution:

out1 <- lapply(rasterlist, function(i) extract(i, ex1))
out2 <- lapply(rasterlist, function(i) extract(i, ex2))

N.B. The solution it does not need to be a member of the apply family (although that was the task I set myself) if there is a better, faster, more elegant way please share.

1

1 Answers

1
votes

You could start with combining the regions into a single SpatialPolygons object (maybe they are to begin with?). With your example data that can be done like this:

ex <- do.call(bind, sapply(exlist, function(x) as(x, 'SpatialPolygons')))

In this example (with RasterLayer objects that can be stacked) you can then do

s <- stack(rasterlist)
extract(s, ex)