Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mosaic in r to merge multiple geotiff

I have 50 geotiff files in the same folder. All of them represent elevation data in different parts of the world. I would like to merge certain geotiff files, and I found mosaic in R might help us. I have moved those geotiff into the same folder, and I wrote a R script show below:

setwd()
a<-list.files(pattern="*.tiff",file.name=TRUE)
combind<-merge(a,fun=mean)

However, this script returned an error: error in as.data.frame(y)

May I ask how could I improve my script?

like image 414
Bing-Hong Huang Avatar asked May 08 '18 12:05

Bing-Hong Huang


1 Answers

You can make use of the powerful GDAL functions. From my experience these are much faster than pure R code.

My approach would be with library(gdalUtils):

First, build a virtual raster file (vrt):

library(gdalUtils)
setwd(...)
gdalbuildvrt(gdalfile = "*.tif", # uses all tiffs in the current folder
             output.vrt = "dem.vrt")

Then, copy the virtual raster to a actual physical file:

gdal_translate(src_dataset = "dem.vrt", 
               dst_dataset = "dem.tif", 
               output_Raster = TRUE # returns the raster as Raster*Object
                                    # if TRUE, you should consider to assign 
                                    # the whole function to an object like dem <- gddal_tr..
               options = c("BIGTIFF=YES", "COMPRESSION=LZW"))

Another pure (and probably slower) raster package solution would be:

f <- list.files(path = "your/path", pattern = ".tif$", full.names = TRUE)
rl <- lapply(f, raster)

do.call(merge, c(rl, tolerance = 1))

you have to adjust the tolerance since the raster files will probably not have the same origin.

like image 116
loki Avatar answered Nov 01 '22 15:11

loki