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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With