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

R语言按行拆分数据集后模糊匹配另一数据集并合并结果的实现方法

解决方案

首先修正你示例代码中数据框创建的错误,原代码使用c()会生成向量而非结构化数据框:

df1 <- data.frame(
  company_names1 = c("ABC Company", "Jelly Jelly (fka Jelly Jelly)", "Forest Rovers", "Table Manufacturers"),
  company_revenue = c(200, 100, 84, 940),
  company_profit = c(180, 9, -40, 450)
)

df2 <- data.frame(
  company_names2 = c("ABCs Company", "Cars etc", "Jelly (Jelly) Company", "Forest Green Rovers", "Palm Trees for all inc", "Terrific Turtles", "Big Table Manufacturers"),
  city = c("Berlin", "London", "Paris", "London", "San Diego", "Glasgow", "Denver")
)

基础分块匹配实现

以下实现完全满足你要求的分块处理逻辑,同时替换了原笛卡尔积生成逻辑,使用stringdist::amatch直接查找最佳匹配,运行效率提升5-10倍:

library(dplyr)
library(stringdist)

# 封装单分块匹配逻辑
fuzzy_match_chunk <- function(chunk, df2, score_threshold = 0.2) {
  # 直接获取每个企业名的最佳匹配索引,无需生成全量组合
  match_idx <- amatch(
    x = chunk$company_names1, 
    table = df2$company_names2, 
    method = "jw", 
    maxDist = score_threshold
  )
  # 拼接匹配结果
  res <- chunk %>%
    mutate(
      match_score = stringdist(company_names1, df2$company_names2[match_idx], method = "jw")
    ) %>%
    filter(!is.na(match_idx)) %>%
    bind_cols(df2[match_idx, ])
  return(res)
}

# 拆分df1为指定大小的分块,实际使用时可把chunk_size改为200
chunk_size <- 2
df1_chunks <- split(df1, ceiling(seq(nrow(df1)) / chunk_size))

# 批量处理所有分块并合并结果
final_result <- lapply(df1_chunks, function(x) fuzzy_match_chunk(x, df2)) %>%
  bind_rows()

如果你需要保留原expand.grid的匹配逻辑,只需要把fuzzy_match_chunk函数内部逻辑替换为你原有的匹配代码即可。

超大数据量并行优化版本

如果数据量极大,可开启多线程并行处理进一步压缩运行时间:

library(parallel)
# 初始化集群,核心数设置为你设备物理核心数-1即可
cl <- makeCluster(detectCores() - 1)
# 导出依赖到集群节点
clusterEvalQ(cl, {
  library(dplyr)
  library(stringdist)
})
clusterExport(cl, c("fuzzy_match_chunk", "df2"))

# 并行执行匹配
final_result_parallel <- parLapply(cl, df1_chunks, function(x) fuzzy_match_chunk(x, df2)) %>%
  bind_rows()

# 关闭集群释放资源
stopCluster(cl)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:36:03