KO 88
KO 88

Reputation: 155

How to extract rasters with the same extent from a list of rasters in R

I have a list object made up of rasters and there are two types of rasters in it in terms of their extent. How can I extract the ones with the same extent and save them as a new list in R? It is not possible to give a reproducible example but the code below can help you understand the question.

A hypothetical example:

library(raster)
list_raster # Suppose this is a list having 48 rasters.
names(list_raster) <- paste0("raster", seq(1:48)) # Assigning names makes it possible to use the dollar sign.
lapply(list_raster, extent) # Gives 48 results but only two unique raster extents.
#  I would like to know which of the rasters has == extent(list_rasters$raster1)

Upvotes: 0

Views: 403

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You can use sapply:

same_as_r1 <- sapply(list_raster, function(x) extent(x) == extent(list_raster$raster1))

And subset your list with it:

group1 <- list_raster[same_as_r1]
group2 <- list_raster[!same_as_r1]

Upvotes: 1

Related Questions