首页 > 解决方案 > 基于R中的部分字符串匹配查找值

问题描述

我有一张包含一堆城市的表(表 1)(标点符号、大写字母和空格已被删除)。

我想扫描第二个表(表 2)并提取与其中任何位置完全匹配或包含字符串的任何记录(第一个)。

# Table 1
  city1    
1 waterloo 
2 kitchener
3 toronto  
4 guelph   
5 ottawa


# Table 2
  city2
1 waterlookitchener  
2 toronto  
3 hamilton  
4 cityofottawa  

这将给出下面看到的第三张表。

# Table 3
  city1      city2
1 waterloo   waterlookitchener  
2 kitchener  waterlookitchener  
3 toronto    toronto  
4 guelph     <N/A>  
5 ottawa     cityofottawa

标签: r

解决方案


您也可以尝试使用fuzzyjoin. 在这种情况下,您可以使用包中的函数stri_detect_fixedstringi识别字符串中至少出现一次固定模式。

library(fuzzyjoin)
library(stringi)
library(dplyr)

fuzzy_right_join(table2, table1, by = c("city2" = "city1"), match_fun = stri_detect_fixed) %>% 
  select(city1, city2)

输出

      city1             city2
1  waterloo waterlookitchener
2 kitchener waterlookitchener
3   toronto           toronto
4    guelph              <NA>
5    ottawa      cityofottawa

数据

table1 <- structure(list(city1 = c("waterloo", "kitchener", "toronto", 
"guelph", "ottawa")), class = "data.frame", row.names = c(NA, 
-5L))

table2 <- structure(list(city2 = c("waterlookitchener", "toronto", "hamilton", 
"cityofottawa")), class = "data.frame", row.names = c(NA, -4L
))

推荐阅读