vanguard605
vanguard605

Reputation: 11

Resampling multiple rasters with a for loop

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

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47036

You had the following mistakes

  1. You were using allrasters[i] outside of the for-loop
  2. you need to use double brackets to extract something from a list as in allrasters[[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
  3. Inside the loop you overwrite the same variable rs so you might as well only do the last iteration. Instead, add the rasters to a list
  4. You resampled the first raster with itself. That is not wrong, but it makes no sense

The 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

Related Questions