R处理wordclim未来数据

library(terra)
library(stringr)
library(purrr)

# 设置路径
input_dir <- "E:/03Phd/20240810-蒙古国甘草/20240805-gancao/0data/未来气候2.5"
output_dir <- "E:/03Phd/20240810-蒙古国甘草/20240805-gancao/0data/分割结果"

# 主处理函数(已修复)
process_climate_file <- function(file_path) {
  file_name <- basename(file_path)
  elements <- str_split(file_name, "_", simplify = TRUE)
  
  # 修正索引位置
  model <- elements[4]    # 第4段是模型名称
  ssp <- elements[5]      # 第5段是SSP情景
  period <- str_replace(elements[6], "\\.tif", "")  # 第6段是时间段
  
  rst <- rast(file_path)
  
  # 创建输出目录
  output_subdir <- file.path(output_dir, ssp, period)
  dir.create(output_subdir, recursive = TRUE, showWarnings = FALSE)
  
  # 分割保存
  walk(1:nlyr(rst), function(band) {
    output_name <- sprintf(
      "%s_%s_%s_bio%02d.tif", 
      model, ssp, period, band
    )
    writeRaster(
      rst[[band]],
      filename = file.path(output_subdir, output_name),
      filetype = "GTiff",
      overwrite = TRUE,
      gdal = c("COMPRESS=LZW")
    )
  })
}

# 执行处理
list.files(input_dir, pattern = "\\.tif$", full.names = TRUE) %>% 
  walk(process_climate_file)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注