Search code examples
rmergetiffgdalrgdal

merging .tif files via gdalbuildvrt not working


I have a piece of code that I have used for a while now to transform .xyz files to .tif and then merge all those .tif files into one big .tif. It has worked well when I last used it 2 years ago, but it seems like the current updates/discontinuation of packages have lead to some malfunctions. The error occurs, when I'm trying to build a vrt of all my .tif tiles (that's 1237). The code looks like this:

setwd()

#merge all .tif files from the list
gdalbuildvrt(gdalfile = source,
             output.vrt = "dem.vrt")

For source I have tried to use ".tif$" as well as ".tif" and basically every possible way to spell it, but it returned the following error:

  running command '"C:\Program Files\QGIS 3.22.6\bin\gdalbuildvrt.exe" "dem.vrt" "*.tif"' had status 1
NULL 

Some research showed that this is a known problem (even though I never encountered it before), and that a workaround is to put all files into a list and run the list as source instead:

#create a list from all .tif files 
list <- list.files(path ="H:/Masterarbeit/R/DGM Oderbruch", pattern = '.tif$', all.files = TRUE, full.names = TRUE) 

allrasters <- lapply(list, raster)

I have tried list as well as allrasters for source, but nothing worked. However, the error message changed to:

Error in system(cmd, intern = TRUE) : 
  'CreateProcess' failed to run 'C:\PROGRA~1\QGIS32~1.6\bin\GDALBU~1.EXE "dem.vrt" "H:/Masterarbeit/R/DGM Oderbruch/dgm_33426-5850.tif" "H:/Masterarbeit/R/DGM Oderbruch/dgm_33426-5851.tif" "H:/Masterarbeit/R/DGM Oderbruch/dgm_33426-5852.tif" "H:/Masterarbeit/R/DGM Oderbruch/dgm_33426-5853.tif" "H:/Masterarbeit/R/DGM Oderbruch/dgm_33426-5854.tif" "H:/Masterarbeit/R/DGM Oderbruch/dgm_33426-5855.tif" "H:/Masterarbeit/R/DGM Oderbruch/dgm_33426-5856.tif" "H:/Masterarbeit/R/DGM Oderbruch/dgm_33426-5857

If anyone has an idea as to why my code stopped working, I would really appreciate it.


Solution

  • You can do

    library(terra)
    ff <- list.files(path =".", pattern = '\\.tif$', full.names = TRUE) 
    
    v <- vrt(ff, "dem.vrt")
    writeRaster(v, "out.tif")