Tainá Rocha
Tainá Rocha

Reputation: 43

Is there a way to write single band raster from multiple raster stacks

I have 4 subfolder that contains 5 rasters with continuous values. So a build a loop with "for" function to :

  1. list these raster files
  2. stack these files per folder , i.e 4 rasterstacks objects (that contains 5 rasters)
  3. I apllied a treshold to transform the the continuous raster in binary raster
  4. Finally I wrote the binary raster using wirte.raster function.

My issue is in a step 4. Eventhough I use the argument "byLayer = T" in writeRaster function the rasters saved were a rasterstack with the 5 binary rasters. And i want write it per raster, per file, per band

I really grateful if anyone give me any insights

setwd("Vole_raw_mean_Present/")

sub <- list.dirs(full.names=FALSE, recursive=FALSE)

for(j in 1:length(sub)) {
  print(sub[j])

  h <- list.files(path=sub[j], recursive=TRUE, full.names=TRUE,  pattern='.tif')
  print(h)

  stack_present <- stack(h)
  print(stack_present)

  binary_0.2 <- stack_present >=0.2

  writeRaster(binary_0.2, filename=paste0(sub[j], bylayer = T, suffix = "_bin.tif"), overwrite=TRUE)

}

Upvotes: 0

Views: 282

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

This is wrong because the argument "bylayer" is lost as it becomes part of the filename)

 writeRaster(binary_0.2, filename=paste0(sub[j], bylayer = T, suffix = "_bin.tif"), overwrite=TRUE)

It should be something like this (and it helps to do it in two steps)

 f <- paste0(sub[j], "bin.tif")
 writeRaster(binary_0.2, filename=f, bylayer=TRUE, overwrite=TRUE)

Illustrated here

library(raster)
b <- brick(system.file("external/rlogo.grd", package="raster"))
dir.create("test")
setwd("test")
writeRaster(b, filename="abc.tif", bylayer=T)
list.files()
#[1] "abc_1.tif" "abc_2.tif" "abc_3.tif"

writeRaster(b, filename="bin.tif", bylayer=T, suffix = paste0("f", 1:3))
list.files(pattern="bin")
#[1] "bin_f1.tif" "bin_f2.tif" "bin_f3.tif"

Alternatively, you can loop over the files within each folder

Upvotes: 1

Related Questions