TransWikia.com

How to keep same extent for my 10 raster files?

Geographic Information Systems Asked by Ali Rawail on March 24, 2021

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

library(raster)
# 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

One Answer

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)

s
#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 

Answered by Robert Hijmans on March 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP