You need to enable JavaScript to run this app. R中如何按文件夹循环,用同目录shapefile裁剪栅格?
优惠活动
大模型
产品
解决方案
定价
更多

R中如何按文件夹循环,用同目录shapefile裁剪栅格?

同目录配套shp批量裁剪tif的R脚本修正

原代码核心报错原因

  • 存在未定义对象引用:代码中写了dirs_especies_names[x],但实际只定义了dirs_especies_path,运行会直接报“找不到对象”的错误
  • 循环逻辑失效:内层裁剪循环固定赋值y=1,无论循环走到哪个索引,永远只会取当前文件夹的第一个tif文件,无法完成全量栅格处理
  • 空间对象读取错误:直接将shp的路径字符串传入crop()、mask()函数,没有先将shp读取为可识别的空间矢量对象,函数无法正确识别裁剪范围
  • 输出逻辑错误:writeRaster环节引用了未定义的i、stac变量,也没有为每个裁剪后的栅格设置独立的输出文件名,同时脚本没有提前创建输出的cut目录,会报路径不存在错误
  • 返回值类型不匹配:用map_df处理栅格输出,和函数预期的返回值类型不兼容,无法正常运行

修正后可直接运行的脚本

# 加载依赖包
library(raster)
library(rgdal)

# 定义根工作路径
path_general <- "H:/Tesis_maestria/1_Eliposides/1_Cut_models"
# 提前创建统一的裁剪结果输出目录
cut_output_dir <- file.path(path_general, "cut_results")
dir.create(cut_output_dir, showWarnings = FALSE, recursive = TRUE)

# 读取根目录下所有一级子文件夹(即对应不同物种的文件夹)
sp_dirs <- list.dirs(path_general, full.names = TRUE, recursive = FALSE)

# 逐文件夹执行批量裁剪
for (sp_dir in sp_dirs) {
  # 跳过自建的输出目录,避免无效遍历
  if (sp_dir == cut_output_dir) next

  # 获取当前物种文件夹内的所有tif文件路径
  tif_list <- list.files(sp_dir, pattern = "\\.tif$", full.names = TRUE)
  # 获取当前物种文件夹内的shp文件路径
  shp_list <- list.files(sp_dir, pattern = "\\.shp$", full.names = TRUE)

  # 跳过缺少tif或缺少shp的异常文件夹,不中断整体流程
  if (length(tif_list) == 0 | length(shp_list) == 0) next

  # 读取当前文件夹内的shp为空间矢量对象
  cut_boundary <- readOGR(dsn = shp_list, verbose = FALSE)
  # 获取当前文件夹的物种名,用于输出文件命名
  sp_tag <- basename(sp_dir)

  # 逐tif执行裁剪
  for (tif_file in tif_list) {
    # 读取原始栅格
    r_origin <- raster(tif_file)
    # 按shp范围裁剪范围,再做掩膜提取
    r_cropped <- crop(r_origin, cut_boundary)
    r_final <- mask(r_cropped, cut_boundary)
    # 拼接输出文件路径:带物种名+原tif名,避免不同物种的同名文件覆盖
    out_path <- file.path(
      cut_output_dir,
      paste0(sp_tag, "_", tools::file_path_sans_ext(basename(tif_file)), "_cut.tif")
    )
    # 写出裁剪结果
    writeRaster(r_final, filename = out_path, format = "GTiff", overwrite = TRUE)
  }
}

脚本使用注意事项

  • 所有裁剪结果统一存放在根目录下的cut_results文件夹中,不会修改原文件夹内的原始数据
  • 自动识别每个文件夹内单独的tif和shp,跨文件夹的文件不会被错误关联处理
  • 支持自动覆盖已存在的旧裁剪结果,重复运行不会报错

内容的提问来源于stack exchange,提问作者Kevin López Reyes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.23 09:24:09