0

I have 16 separate raster files, named by ID and band, for 8 bands and 2 IDs. How can I merge the bands for each ID to create two multi-band TIFFs? Here are my data:

    dput(rastlist)
    c("7398_b10_new.tif", "7398_b2_clip.tif", "7398_b3_clip.tif", 
"7398_b4_clip.tif", "7398_b5_clip.tif", "7398_b6_clip.tif", "7398_b7_clip.tif", 
"7398_pan_new.tif", "9609_b10_new.tif", "9609_b2_clip.tif", "9609_b3_clip.tif", 
"9609_b4_clip.tif", "9609_b5_clip.tif", "9609_b6_clip.tif", "9609_b7_clip.tif", 
"9609_pan_new.tif")

I managed to do it this for the first 8 elements of my list. Here's how:

setwd("mydir")

#first import all files in a single folder as a list 
rlist <- list.files(path = "mydir", pattern='.tif$', all.files=T, full.names=F)

#substract the  first 8 raster of the list
n = tail(rlist,8)

#stack layers
rstack = stack(n)

#substract the first element of the list
one = tail(n, 1)

#get the first 4 letters of the first element of a list (to be used as raster name of the raster stack)
rexport = substr(one, 1, 4)

writeRaster(rstack, filename = rexport, options = "INTERLEAVE=BAND", overwrite = T, format = "GTiff")

How can I generalize this?

3
  • 1
    Is this a better way of posing the question: "I have 16 separate raster files, named by ID and band, for 8 bands and 2 IDs. How can I merge the bands for each ID to create two multi-band TIFFs?" because as its written its a bit unclear to me. Might be worth editing for clarity.
    – Spacedman
    Sep 13, 2021 at 8:18
  • What do you want to generalise it to? Any number of sets of N raster files with names in some pattern?
    – Spacedman
    Sep 13, 2021 at 13:04
  • I want to create a function that takes a list of N raster (multiple of 8, e.g. 16, 24, 32 etc), performs the above code to the first 8 raster of the list, then then next 8 and so on.
    – Nikos
    Sep 13, 2021 at 15:01

1 Answer 1

0

Solved

  rlist <- list.files(path = "mydir", pattern=paste0(ras, ".*.tif$"), all.files=T, full.names=F)
  rstack = stack(rlist)
  writeRaster(rstack, filename = rexport, options = "INTERLEAVE=BAND", overwrite = T, format = "GTiff")
}

rass <- unique(substring(rastlist, 1, 4))

lapply(rass, stacker)

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.