[GIS] Importing several GeoTiff files into R

geotiff-tiffrrgdal

I think that must be a "simple" way to import several Geotiff files into R instead of copy and paste n times Rfd<-readGDAL() and then save them as individual objects.

I found the following code in a post regarding how to import multiple shapefiles …

get all files with the .shp extension from working directory
setwd("D:/GIS_DataBase/GIS_Tirol/Tirol_Verbreitungskarten/Verbreitungs_Daten")
shps <- dir(getwd(), "
.shp")
the assign function will take the string representing shp and turn it into a variable
which holds the spatial points data
for (shp in shps) assign(shp, readShapePoints(shp))
plot(get(shp[1])) # i.e.
…done*

But it does not translate to raster files with readGDAL {rgdal} function.

Other post suggested the use of for or/and function, when importing several *.csv files into R. However, I have been equally unsuccessful into make it work.

Best Answer

A simple for loop will suffice. You can use readGDAL in the rgdal package but I would recommend raster in the raster package. You have to be a bit tricky and use strsplit in the assign function to strip off the ".tif" file extension.

setwd("C:/rasters")
rlist=list.files(getwd(), pattern="tif$", full.names=FALSE)
for(i in rlist) { assign(unlist(strsplit(i, "[.]"))[1], raster(i)) } 

If your data aligns (same resolution, origin coordinates, extent, number of rows and columns) then it is is as simple as passing the rlist object to the raster stack or brick function. This results in a single object containing all of the rasters. Even if your rasters are not aligned, you can use the "quick=TRUE" argument, which will skip consistency checks. The resulting stack object will contain all of the designated rasters and you can slit them into individual raster class objects.

Both the stack and brick functions have internal looping and will accept a list of rasters and the rasters can be single or multiple band.

Related Question