1

I have 64 TIFF files of different dates, each date has 4 bands (123 and 4 for B, G R and NIR). I am trying to develop a Vegetation index for each date image. This is how the images in my folder are

[1] "20171106.tif"     "20171106.tif.ovr" "20171113.tif"     "20171113.tif.ovr" "20171121.tif"     "20171121.tif.ovr" ........................................
 [64] "20171208.tif"  

I used this command to process one single date image to get my index

st <- stack("20171106.tif")
br <- brick(st)
gcvi20171106 <- (br[[4]]/br[[2]])-1
plot(gcvi20171106) 

But if I have to do it 64 times by manually changing the names its tedious.

I tried this loop

setwd("D:\\AP\\all_images\\")
lst <- list.files()
lngth <- length(lst)
rlist <- lapply(lst, raster)
for (i in 1:64){
  stk <- stack(rlist[i])
  brik[i] <- brick(stk[i])
  gcvi[i] <- (brik[[4]]/brik[[2]])-1
  }

I am new to loops. How can I do this?

0

One approach is to write a function and apply it across all of your datasets using lapply. For example:

require(raster)

# Define the input and output workspaces
inws <- '/path/to/input_workspace'
outws <- '/path/to/output_workspace'

# Get a list of tif files from inws
files <- list.files(inws, pattern = "*.tif", full.names = TRUE)

# Function to calculate GCVI veg index and write to raster
gcvi <- function(path, nir_band = 4, green_band = 2){
  img <- stack(path)
  nir <- img[[nir_band]]
  green <- img[[green_band]]
  vi <- (nir/green) - 1

  writeRaster(vi, file.path(outws, paste(tools::file_path_sans_ext(basename(path)), '_gcvi.tif', sep = "")))
}

# Apply the function across all files in inws
lapply(files, gcvi)
| improve this answer | |
  • Many thanks, your code worked. – user1 Feb 20 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.