DigitalAG
DigitalAG

Reputation: 41

Iterating through every folders and choosing selected bands

I have several folders each one of which contains several bands of Landsat 8. I want to iterate through each folder and choose same 4 specific bands. The bands in each folder are arranged in same order, due to which a query can be made on basis of their listing value.

Here is my code, but its not working.

library(raster)
library(rgdal)
setwd("Z:/TasseledCap")
folders <- list.dirs()
for(f in 1:length(folders)){
  rasterlist<-list.files(folders[f], full.names=FALSE)
  rasterlist
  B <- raster(rasterlist[4])
}

"Error in .local(.Object, ...) :
`Z:\TasseledCap\LC80330302015211LGN00_B1.TIF' does not exist in the file system, and is not recognised as a supported dataset name.

Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer", : Cannot create a RasterLayer object from this file. (file does not exist)

Upvotes: 0

Views: 62

Answers (1)

maRtin
maRtin

Reputation: 6516

Setting the full.names argument to TRUE should fix your problem. Note that your code will overwrite the B variable in each iteration.

setwd("Z:/TasseledCap")
folders=list.dirs()

for(f in 1:length(folders)){
    rasterlist < -list.files(folders[f], full.names=TRUE)
    B <- raster(rasterlist[4])
}

P.S.: Changing the working directory with setwd() isn't always the best idea. I would try to avoid this command:

root    <- "Z:/TasseledCap"
folders <- list.dirs(root, recursive=F)

for(f in 1:length(folders)){
    rasterlist <- list.files(folders[f], full.names=TRUE)
    B <- raster(rasterlist[4])
}

Upvotes: 1

Related Questions