Crop multiple rasters using map or mapply?

by BonnieM   Last Updated July 12, 2019 21:22 PM

I have a folder of rasters with slightly different extents. I would like to apply crop to the whole list of rasters. I'm trying to teach myself how to use the purrr map family, but I can't get that or mapply to apply a function with multiple arguments to a list of files, i.e.

# reproducible example raster w/ categorical values
# from: https://stackoverflow.com/questions/9940495/plot-raster-factir-values-with-ggplot
library(raster)

f <- system.file("external/test.grd", package="raster")
r <- raster(f)
r <- reclassify(r, c(0, 500, 1,  # from, to, becomes
                     500, 2000, 2))
levels(r)
rcat <- as.factor(r)
levels(rcat)  # 2 levels
extent(rcat)
# make second raster of slightly different extent
extnew1 <- as(extent(178000, 181520, 329400, 334000), "SpatialPolygons")
rcat2 <- crop(rcat, extnew1)
extent(rcat2)

# list of rasters with different extents
mylist <- list(rcat, rcat2)
unique(map(mylist, extent))  # different extents

# crop both to smaller extent
extnew2 <- as(extent(178400, 181500, 329300, 334000), "SpatialPolygons")

# does not work
rcat_crop <- map(mylist, crop, extnew2)

unique(map(rcat_crop, extent)) # matches smallest extent of rasters, not new extent

# does not work
rcat_crop <- mapply(FUN=crop, MoreArgs=list(x=mylist, y=extnew2))

length(rcat_crop)  # =0

What am I doing wrong?

Related question on how to crop using R

Tags : raster r clip extents


Related Questions




Deleting vector lines beyond image extents using QGIS?

Updated January 12, 2017 09:09 AM

Batch processing of Gdal clip function

Updated April 13, 2019 13:22 PM