Essentially, you want to look at raster::extract
, then look if there are any values in the vector that is returned. I have an example here that makes 10 rasters in a list, adds a value to the even number rasters, makes a polygon to extract with, then sapply
over the raster list finding any vectors from extract
that have a value.
library(raster)
library(sp)
## make rasters, evens have a 1 at index 58
rasts <- lapply(1:10, function(x) raster(matrix(rep(NA, 100), ncol = 10)))
hasValue <- seq(2, 10, 2)
rasts[hasValue] <- lapply(rasts[hasValue], function(x){x[58] <- 1; return(x)})
## check that evens have a value
which(sapply(rasts, function(x) any(!is.na(getValues(x)))))
## make spatial polygon
x <- c(0.5, 0.6, 0.9)
y <- c(0.6, 0.2, 0.6)
checkArea <- SpatialPolygons(list(Polygons(list(Polygon(list(matrix(c(x, x[1], y, y[1]), ncol = 2)))), ID = 1)))
## check for values in polygon
checkForValueInPolygon <- function(rast){
any(!is.na(raster::extract(rast, checkArea)[[1]]))
}
rastersWithValue <- which(sapply(rasts, checkForNaInPolygon))
## does rasters with value match hasValue?
all(hasValue %in% rastersWithValue) & all(rastersWithValue %in% hasValue)