Search code examples
terra

How to avoid memory issues when creating a mosaic of raster tiles using terra?


I have a list containing 375 raster tiles that I would like to mosaic into one raster:

filelist_lc <- list.files("Northern_Land_Cover_2000/")
lc_2000_tiles <- lapply(filelist_lc, rast)

> lc_2000_tiles[[1]]
class       : SpatRaster 
dimensions  : 4962, 5049, 1  (nrow, ncol, nlyr)
resolution  : 30, 30  (x, y)
extent      : 1614258, 1765728, 8094905, 8243765  (xmin, xmax, ymin, ymax)
coord. ref. : LCC         E008 
source      : 014M.tif 
name        : 014M 

lc_2000_tiles[[2]]
class       : SpatRaster 
dimensions  : 4791, 4747, 1  (nrow, ncol, nlyr)
resolution  : 30, 30  (x, y)
extent      : 1462288, 1604698, 8381835, 8525565  (xmin, xmax, ymin, ymax)
coord. ref. : LCC         E008 
source      : 015L.tif 
name        : 015L 

....

I was trying to figure out a way to use mosaic them. This was the solution I came up with. However, after 7 tiles are combined, the computer runs out of disk space.

Error: [merge] internal error: insufficient disk space (perhaps from temporary files?)

Is there a more efficient way to do this?


Solution

  • You do not show what you do with lc_2000_tiles. Do you provide a filename argument? If not, the output goes to the temp folder, and perhaps this is on disk with not much space (and it is inefficient). You can set the temp folder with terraOptions(tempdir = "....")

    Also, do you need mosaic or can you use merge (equivalent if you have non-overlapping areas)? If so, you can also use vrt:

    v <- vrt(filelist_lc)
    

    A "VRT" is a virtual raster. It can treat different files (typically adjacent non-overlapping tiles, but that is not required) as a single data source (file). With that, you could then do

    x <- writeRaster(v, "combined.tif")