I am not able to keep same extent for my raster files and stack them together.

# for reproducible example
r1 <- raster(xmn=72.23081, xmx=77.79537, ymn=34.26277, ymx=37.35659,res=1)
values(r1) <- 1:ncell(r1)
r2 <- raster(xmn=72.51037, xmx=77.68996, ymn=34.51186, ymx=37.098,res=1)
values(r2) <- 1:ncell(r2)
r3 <- raster(xmn=72.2514, xmx=77.9430, ymn=34.20765, ymx=37.40778,res=1)
values(r3) <- 1:ncell(r3)

rasters <- list(r1, r2, r3)
s <- stack(rasters)
# Error in compareRaster(x) : different extent

1 Answer 1


I already answered your question here.

You have rasters for the same area but with slightly different extents. The first question to ask is why? How were these files generated? They should probably be re-generated so that they do have the same extent. You can also use resample, but then there is some data quality loss. Here is how you can use resample with the example data

for (i in 2:length(rasters)) {
     rasters[[i]] <- resample(rasters[[i]], r1)
s <- stack(rasters)

#class      : RasterStack 
#dimensions : 3, 6, 18, 3  (nrow, ncol, ncell, nlayers)
#resolution : 1, 1  (x, y)
#extent     : 72.23081, 78.23081, 34.35659, 37.35659  (xmin, xmax, ymin, ymax)
#crs        : +proj=longlat +datum=WGS84 +no_defs 
#names      :  layer.1,  layer.2,  layer.3 
#min values :  1.00000, -0.57251,  1.28655 
#max values : 18.00000, 13.42749, 18.28655 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.