How to keep same extent?

851 Views Asked by At

I have 10 raster files. I want to stack them. How to keep same extent for all these 10 files ?

library(raster)

rasterfile <- list.files(file.path("E:/NDVI RESULT FINAL"), full.names = T, pattern = '.tif$')

f1 <- "E:/NDVI RESULT FINAL/NDVI converted 2009.tif"
r1 <- raster(f1)
f2 <- "E:/NDVI RESULT FINAL/NDVI converted 2010.tif"
r2 <- raster(f2)
f3 <- "E:/NDVI RESULT FINAL/NDVI converted 2011.tif"
r3 <- raster(f3)
# and so on

extent(rasterf1) 
#class : Extent xmin : 72.23081 xmax : 77.79537 ymin : 34.26277 ymax : 37.35659 
extent(rasterf2)
#class : Extent xmin : 72.51037 xmax : 77.68996 ymin : 34.51186 ymax : 37.098
extent(rasterf3) 
#class : Extent xmin : 72.2514 xmax : 77.94309 ymin : 34.20765 ymax : 37.40778
extent(rasterf4)
#class : Extent xmin : 72.23081 xmax : 77.79537 ymin : 34.26277 ymax : 37.35659

etcetera

1

There are 1 best solutions below

5
On

Normally, you would do

ff <- list.files(file.path("E:/NDVI RESULT FINAL"), full.names = T, pattern = '.tif$')
s <- stack(ff)

Does this not work? If so, you can do something like this to see what the extents are.

# example data 
f <- (system.file("external/rlogo.grd", package="raster")) 
ff <- c(f, f, f)

x <- lapply(ff, raster)
t(sapply(x, function(i) as.vector(extent(i))))
#    [,1] [,2] [,3] [,4]
#[1,]    0  101    0   77
#[2,]    0  101    0   77
#[3,]    0  101    0   77

Later:

You have now shows that all the extents are different. 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.

Example data

library(raster)
r1 <- raster(ncol=10, nrow=10, xmn=0, xmx=1, ymn=0, ymx=1, vals=1:100)
r2 <- shift(r1, .5)
r3 <- shift(r1, .5, .5)
r4 <- shift(r1, 0, -.5)

Problem

stack(r1, r2)
#Error in compareRaster(x) : different extent

Solution

rsts <- list(r1, r2, r3, r4)
for (i in 2:length(rsts)) {
     rsts[[i]] <- resample(rsts[[i]], r1)
} 
s <- stack(rsts)
s
#class      : RasterStack 
#dimensions : 10, 10, 100, 4  (nrow, ncol, ncell, nlayers)
#resolution : 0.1, 0.1  (x, y)
#extent     : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
#crs        : +proj=longlat +datum=WGS84 +no_defs 
#names      : layer.1, layer.2, layer.3, layer.4 
#min values :       1,       1,      51,       1 
#max values :     100,      95,      95,      50