有没有办法从多个栅格堆栈中写入单波段栅格

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

我有 4 个子文件夹,其中包含 5 个具有连续值的栅格。所以用 "for" 函数构建一个循环到 :

  1. 列出这些光栅文件
  2. 每个文件夹堆叠这些文件,即 4 个 rasterstacks 对象(包含 5 个光栅)
  3. 我应用了一个阈值来转换二进制栅格中的连续栅格
  4. 最后我使用 wirte.raster 函数编写了二进制栅格。

我的问题在步骤 4 中。尽管我在 writeRaster 函数中使用了参数 "byLayer = T" 保存的栅格是一个包含 5 个二进制栅格的栅格堆栈。我想按光栅、文件、波段写

如果有人给我任何见解,我真的很感激

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)

}

这是错误的,因为参数 "bylayer" 在成为文件名的一部分时丢失了)

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

应该是这样的(而且分两步做会有帮助)

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

此处有插图

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"

或者,您可以遍历每个文件夹中的文件