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

如何在R中用match和grepl匹配地址模式并填充对应列值?

R语言实现地址模式匹配并关联ID列

需求说明

通过匹配两个数据框中的地址核心内容,将df2中的ID值对应插入到df1的对应行中,最终得到包含Names、原Address和对应ID的结果数据框。

数据准备

首先定义两个输入数据框:

df1 <- structure(list(Names = c("A", "B", "C"), 
                      Address = c("101, 16 Ave NE", "203, 4 Cross SE", "115, 48 Ave SW")), 
                 class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -3L))

df2 <- structure(list(ID = c(1415, 2106, 2107), 
                      Address = c("101 16 Ave", "115 48 Ave SW Cresmont", "203 Skyview 4 Cross SE Near Walmart")), 
                 class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -3L))

解决方案

通过提取地址核心关键词,结合字符串检测实现精准匹配,具体代码如下:

library(tidyverse)

df_result <- df1 %>%
  rowwise() %>%
  mutate(
    # 清理地址:去掉逗号
    clean_addr = str_replace(Address, ",", ""),
    # 构建核心匹配关键词:移除地址末尾的方向后缀(如NE/SE/SW)
    core_addr = str_remove(clean_addr, "\\s[NS][EW]$"),
    # 在df2中找到匹配的行索引
    match_pos = which(str_detect(df2$Address, clean_addr) | str_detect(df2$Address, core_addr)),
    # 提取对应ID
    ID = df2$ID[match_pos]
  ) %>%
  # 保留目标列
  select(Names, Address, ID)

# 查看结果
print(df_result)

输出结果

运行上述代码后,将得到符合期望的结果:

# A tibble: 3 × 3
  Names Address            ID
  <chr> <chr>           <dbl>
1 A     101, 16 Ave NE   1415
2 B     203, 4 Cross SE  2107
3 C     115, 48 Ave SW   2106

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:21:42