I am storing ~ 30 raster files in a folder and want to create a raster stack. I know that not all of these rasters have completely the same extent. They do have the same resolution and CRS.
Thus I try to set the same extent for all of my rasters in this folder with the following loop in R.
#reference raster to get the extent
a <- raster("F:/SDM/DATA/env_tiff/e_veg_d10.tif")
# where the new rasters will be stored
outpath <- "F:/SDM/DATA/temp/"
dir.create(outpath)
files <- list.files(path="F:/SDM/DATA/env_tiff", pattern=".tif$")
# add output directory
outfiles <- paste0(outpath, files)
# change extensions
extension(outfiles) <- 'tif'
for(i in 1:length(files)) {
e <- extent(a)
r <-raster(files[i])
rc <- crop(r, e)
rc<- mask(rc, e)
rw <- writeRaster(rc, outfiles[i], overwrite=TRUE)
print(outfiles[i])
}
#creates a raster stack with all environmental rasters in this file
env_data <- list.files(path="F:/SDM/DATA/temp", pattern = 'tif$')
env_data<- stack(env_data)
For my loop I get the following Error message:
Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘mask’ for signature ‘"RasterLayer", "Extent"’
When I comment the mask part, the loop works, but the extents are still different.
I am also not sure if I choose the right extent, since I don't know the minimum extent. I spent a lot of time searching a way to handle this multiple-extent-problem within my data and found the crop()
and mask()
functions.