【问题标题】:How can I merge the bands for each ID to create two multi-band TIFFs in R?如何合并每个 ID 的波段以在 R 中创建两个多波段 TIFF?
【发布时间】:2021-09-17 12:21:14
【问题描述】:

我有 16 个单独的光栅文件,分别以 ID 和波段命名,用于 8 个波段和 2 个 ID。如何合并每个 ID 的波段以创建两个多波段 TIFF?这是我的数据:

    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")

我设法为列表的前 8 个元素做到了这一点。方法如下:

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")

基本上,我想要的是创建一个函数,每 8 个栅格执行一次上述代码。

【问题讨论】:

  • 如果光栅 ID 是每个光栅文件名的前缀,你能在一个循环中使用你现有的代码吗?
  • 试了很多次还是搞不定。

标签: r function


【解决方案1】:

循环遍历每个唯一 ID:

for(ras in unique(substr(rastlist, 1, 4))){
  rlist <- list.files(path = "mydir", pattern=paste0(ras, '*.tif$'), all.files=T, full.names=F)
  rstack = stack(rlist)
  writeRaster(rstack, filename = paste0(ras, ".tif"), options = "INTERLEAVE=BAND", overwrite = T, format = "GTiff")
}

或者,同样的事情,但作为一个函数,就像你在问题中所说的那样:

stacker <- function(ras){
  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)

【讨论】:

  • 我正在尝试遵循您的建议,但我没有得到正确的结果。在for loopfunction 中我都收到错误Error in .local(x, ...) : no filenames supplied。这是为什么呢?
  • 听起来您没有找到任何带有list.files() 的文件。如果你运行rlist,你会得到什么?
  • rlist [1] "7398_b10_new.tif" "7398_b2_clip.tif" "7398_b3_clip.tif" "7398_b4_clip.tif" "7398_b5_clip.tif" [6] "7398_b6_clip.tif" "7398_b7_clip.tif" "7398_pan_new.tif" "9609_b10_new.tif" "9609_b2_clip.tif" [11] "9609_b3_clip.tif" "9609_b4_clip.tif" "9609_b5_clip.tif" "9609_b6_clip.tif" "9609_b7_clip.tif" [16] "9609_pan_new.tif" 我正在获取光栅文件。我已经对此进行了测试,但我不明白为什么 loopfunction 无法读取文件
  • 逐行运行调试是个好主意。我刚刚在我的机器上测试了这个,我通过修复几个简单的错别字让它工作了。 (1) 确保path=mydir 正确。请注意,如果您使用path="mydir",那是字符串而不是变量。 (2) 更新为pattern=paste0(ras, ".*.tif$)
  • 成功了!干得好 Skaqqs,非常感谢。
猜你喜欢
  • 2013-03-16
  • 2016-09-04
  • 2021-08-26
  • 2021-06-16
  • 2021-06-02
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多