Is it possible to mask and/or crop a raster to multiple polygons, with the output being multiple raster's (i.e., a raster stack)?
Here's a reproducible example:
library(tidyverse)
library(raster)
library(sf)
filename <- system.file("external/test.grd", package="raster")
r <- raster(filename)
# Create a data frame containing the centroids of a polygon
(df <- data.frame(
x = c(180000, 180500),
y = c(331700, 332200)))
# create a point shapefile from the dataframe, then convert to polygon
polygon <- df %>%
st_as_sf(coords = c("x", "y"), crs = crs(r)) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("POINT") %>%
st_buffer(dist=200)
# plot the raster and polygon
plot(r)
plot(polygon, add=TRUE)
# mask and crop the raster
m <- r %>% mask(polygon) %>%
crop(polygon)
The above code returns a single raster. How to return multiple rasters for each polygon?
raster::mask( raster::crop(r, raster::extent(p)), p)