Reputation: 11
I am trying to loop a resample function over some rasters I have in a list so the dimensions, extent, and resolution of them match the first raster in the list. But I keep getting the following error
Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘resample’ for signature ‘"list", "RasterLayer"’
Below is my code:
library(raster)
rastlist <- list.files(path = ".", pattern='.tif$',
all.files=T, full.names=F)
allrasters <- lapply(rastlist, raster)
nrasters <- length(allrasters)
raster_standard <- allrasters[[1]]
r<-allrasters[i]
for (i in 1:nrasters) {
rs<-resample(r,raster_standard, method='bilinear')
}
I have found some similar threads but I don't think I am making the same mistakes so I am not sure the solutions will help me. Any help you can provide will highly appreciated.
Upvotes: 1
Views: 1206
Reputation: 47036
You had the following mistakes
allrasters[i]
outside of the for-loopallrasters[[i]]
--- using single brackets will generate the error message you report, as you would try to use resample
with a list
instead of a RasterLayer
rs
so you might as well only do the last iteration. Instead, add the rasters to a listThe below works
library(raster)
#ff <- list.files(pattern='\\.tif$')
# to make this reproducible
f <- system.file("external/test.grd", package="raster")
ff <- rep(f, 3)
rr <- lapply(ff, raster)
standard <- rr[[1]]
rs <- list(standard)
for (i in 2:length(rr)) {
rs[[i]] <- resample(rr[[i]], standard, method='bilinear')
}
s <- stack(rs)
For faster resampling, you can try terra
library(terra)
rr <- lapply(ff, rast)
standard <- rr[[1]]
rs <- list(standard)
for (i in 2:length(rr)) {
rs[[i]] <- resample(rr[[i]], standard, method='bilinear')
}
s <- rast(rs)
Upvotes: 1