Lena
Lena

Reputation: 321

How to merge raster tiles that have minor differences in origin after reducing resolution with 'aggregate'

I have 29 raster tiles with the following properties:

class       : SpatRaster 
dimensions  : 45000, 45000, 1  (nrow, ncol, nlyr)
resolution  : 0.0008888889, 0.0008888889  (x, y)
extent      : 20, 60, -40, 0  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
data source : N00E020_agb.tif 
names       : N00E020_agb 

I want to merge all 29 tiles into a single raster, however, at this high resolution it takes to long. So I first decreased the resolution of these rasters using aggregate. I aggregate by a factor 113 (roughly leads to a resolution of 0.1):

pathz <- "C:/Users/rastertiles/"                                     # directory where raster tiles are located
filez <- list.files(path = paste(pathz, sep = ""), pattern = ".tif") # list all files in directory

r.list_113 <- list()                                                 # make an empty list

for(i in 1:length(filez)){  
  tmp1 <- rast(paste(pathz, filez[i], sep = ""))
  tmp1 <- terra::aggregate(tmp1,fact=113, fun="mean", na.rm=TRUE)    # aggregate by a factor 113.
  r.list_113[[i]] = tmp1
}

However, while the orignal tiles all have the same origin ([0,0]), after using 'aggregate' the new rasters have minor differences in origin:

> lapply(r.list_113, origin)
[[1]]
[1] 0.01155556 0.00000000

[[2]]
[1] 0.03466667 0.00000000

[[3]]
[1] -0.04266667  0.00000000

[[4]]
[1] -0.01955556  0.00000000

(...)

When I then try to merge the new rasters with 'merge' , I get an error:

> m_113X <- do.call(terra::merge, r.list_113X)
Error: [merge] origin of SpatRaster 2 does not match the previous SpatRaster(s)

Any suggestions what I should do are welcome.

Upvotes: 0

Views: 748

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47491

What version of terra are you using? I ask because I believe that the current version will give a warning but proceed. Also, you could of course aggregate with 100 instead of 113 so that the origins are not changed.

They easiest approach may be to make a virtual raster like this:

v <- vrt(files, "my.vrt")

and then proceed with

r <- rast("my.vrt")

and perhaps

a <- aggregate(r, 100)

Or whatever it is you would like to do.

Upvotes: 1

Related Questions