lorena lorena - 2 years ago 61
R Question

How to efficiently bring in all raster files into R?

I am bringing in 10+ raster files (one-band files, not very big) into R from a folder outside of my working directory. Individually calling the files works, but it's getting tedious. I have seen people use code similar to this:

require(raster)
current.list <- list.files(path="Y:/Spatial/RasterData/current",
pattern =".tif", full.names=TRUE)
c.stack<- stack(current.list)


However, it is raising various errors for me. Including, ".rasterObjectFromFile(x, band = band, objecttype = "RasterLayer", : Cannot create a RasterLayer object from this file. (file does not exist)"

Note, I've tried several different formats (.grd, .img) and often also require(rgdal) prior to running the command. Thanks in advance for your thoughts!

Answer Source

I haven't tested it, but I think if you add a "$" sign to the end of your pattern = ".tif" portion, i.e.:

current.list <- list.files(path="Y:/Spatial/RasterData/current", 
     pattern =".tif$", full.names=TRUE)

...things should work. The "$" symbol essentially means end of string, so you will only list files ending in ".tif" and nothing beyond (e.g. "tif.aux.xml").

Best of luck, and let me know if that doesn't do it for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download