You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中如何按ID合并单波段栅格生成对应多波段TIFF文件

R语言批量合并多波段栅格实现

推荐优先使用按ID自动分组的方案,该方案不依赖文件列表的排序,不会出现文件顺序混乱导致合并错误的问题,实现代码如下:

# 加载所需包
library(raster)

# 设置工作路径
setwd("mydir")

# 读取所有tif文件列表
rlist <- list.files(path = "mydir", pattern='\\.tif$', all.files = TRUE, full.names = FALSE)

# 自定义批量合并函数
batch_stack <- function(file_list){
  # 提取所有文件的ID前缀(前4位)
  ids <- unique(substr(file_list, 1, 4))
  # 遍历每个ID执行合并
  for(id in ids){
    # 筛选当前ID对应的所有8个波段文件
    id_files <- file_list[grep(paste0("^",id), file_list)]
    # 堆叠波段
    rstack <- stack(id_files)
    # 导出文件
    writeRaster(rstack, filename = id, options = "INTERLEAVE=BAND", overwrite = TRUE, format = "GTiff")
  }
  cat("全部", length(ids), "个ID的栅格合并完成!")
}

# 调用函数执行合并
batch_stack(rlist)

如果你确实需要固定按每8个文件拆分执行的版本,实现代码如下:

library(raster)
setwd("mydir")
rlist <- list.files(path = "mydir", pattern='\\.tif$', all.files = TRUE, full.names = FALSE)

# 自定义每8个文件合并的函数
batch_stack_by8 <- function(file_list, per_num = 8){
  # 计算拆分的组数
  group_num <- ceiling(length(file_list)/per_num)
  # 遍历每一组
  for(i in 1:group_num){
    # 提取当前组的文件
    start_idx <- (i-1)*per_num + 1
    end_idx <- min(i*per_num, length(file_list))
    group_files <- file_list[start_idx:end_idx]
    # 堆叠波段
    rstack <- stack(group_files)
    # 提取文件名前缀作为导出名
    rexport <- substr(group_files[1], 1, 4)
    # 导出
    writeRaster(rstack, filename = rexport, options = "INTERLEAVE=BAND", overwrite = TRUE, format = "GTiff")
  }
  cat("全部", group_num, "组栅格合并完成!")
}

# 调用函数执行合并
batch_stack_by8(rlist)

内容的提问来源于stack exchange,提问作者Nikos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 02:30:01