I am an R novice, especially when it comes to spatial data. I am trying to find a way to efficiently import multiple (~600) single-band raster (.tif) files into R, all stored in the same folder. Not sure if this matters but note that, when viewed in a folder on my Mac and Windows Parallel VM, there are the following five (5) file formats for each .tif = .TIF; .tfw; .TIF.aux.xml; .TIF.ovr; .TIF.xml. At any rate, the following code (and other similar variants I've tried) does not seem to work:
library(sp)
library(rgdal)
library(raster)
#path to where all .tif files are located
setwd("/path/to/workingdirectory")
#my attempt to create a list of my .tif files for lapply
temp = list.files(pattern="*.tif")
temp #returns 'character(0)'
#trying to use the raster function to read all .tif files
myfiles = lapply(temp, raster)
myfiles #returns 'list()'
Is there a way to use some form of loop to import all raster files efficiently?
I found the answer and will post the full code to help other beginner R-users who have this issue. To call a list element, use double square brackets [[]], like this:
#first import all files in a single folder as a list
rastlist <- list.files(path = "/path/to/wd", pattern='.TIF$',
all.files=TRUE, full.names=FALSE)
#import all raster files in folder using lapply
allrasters <- lapply(rastlist, raster)
#to check the index numbers of all imported raster list elements
allrasters
#call single raster element
allrasters[[1]]
#to run a function on an individual raster e.g., plot
plot(allrasters[[1]])
Booyah. Thanks to Parfait for help.
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