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

如何在R中基于3位小数键匹配4位小数文件名并复制对应文件

R 批量复制匹配指定规则的二进制文件实现方案

核心匹配逻辑

搜索key为保留3位小数的经纬度组合,待匹配文件名中经纬度保留4位小数,直接通过字符串前缀匹配即可实现精准识别,无需数值转换即可避免精度误差:例如搜索key43.093_-110.531可以直接匹配文件名中包含该字符串前缀的data_43.09375_-110.53125。

完整可运行代码

# 基础参数配置,替换为你自己的实际路径
source_dir <- "待扫描的源文件目录路径"
target_dir <- "文件要复制到的目标目录路径"

# 搜索key列表,可自行增删修改
search_keys <- c(
  "43.093_-110.531",
  "43.093_-110.469",
  "43.093_-110.406",
  "43.156_-110.594",
  "43.156_-110.531",
  "43.156_-110.469",
  "43.156_-110.406",
  "43.156_-110.344",
  "43.156_-110.281",
  "43.218_-110.844",
  "43.218_-110.781",
  "43.218_-110.719",
  "43.218_-110.656",
  "43.218_-110.594",
  "43.218_-110.531"
)

# 生成正则匹配规则
match_rule <- paste0(search_keys, collapse = "|")

# 读取源目录下所有文件
all_source_files <- list.files(source_dir, full.names = TRUE)

# 筛选符合匹配规则的文件
matched_files <- all_source_files[grepl(match_rule, basename(all_source_files))]

# 自动创建不存在的目标目录
if (!dir.exists(target_dir)) dir.create(target_dir, recursive = TRUE)

# 批量复制文件,overwrite参数设为TRUE可覆盖目标目录已有的同名文件
copy_result <- file.copy(
  from = matched_files,
  to = file.path(target_dir, basename(matched_files)),
  overwrite = FALSE
)

# 输出执行结果
cat("执行完成:共匹配到", length(matched_files), "个文件,成功复制", sum(copy_result), "个\n")

特殊场景适配(文件名格式不固定时可选)

如果你的文件名命名规则不固定,可能存在字符串匹配误差,可以改用数值比对逻辑,将文件名和搜索key中的经纬度统一保留3位小数后再匹配:

# 从文件名提取经纬度数值的自定义函数
get_lon_lat <- function(file_path) {
  file_name <- basename(file_path)
  # 提取两个带小数点的数值,适配不同前缀的文件名
  num_part <- regmatches(file_name, gregexpr("-?\\d+\\.\\d+", file_name))[[1]]
  as.numeric(num_part)
}

# 将搜索key转换为保留3位小数的数值矩阵
key_numeric <- do.call(
  rbind,
  lapply(strsplit(search_keys, "_"), function(x) round(as.numeric(x), 3))
)

# 逐文件做数值比对
matched_files <- c()
for (f in all_source_files) {
  lon_lat <- round(get_lon_lat(f), 3)
  # 校验是否和任意一个key匹配
  is_matched <- any(apply(key_numeric, 1, function(k) all(k == lon_lat)))
  if (is_matched) matched_files <- c(matched_files, f)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:36:03