r - R:Regex_Join/Fuzzy_Join - 以不同的词序加入不精确的字符串
问题描述
df1
df2
df3
library(dplyr)
library(fuzzyjoin)
df1 <- tibble(a =c("Apple Pear Orange", "Sock Shoe Hat", "Cat Mouse Dog"))
df2 <- tibble(b =c("Kiwi Lemon Apple", "Shirt Sock Glove", "Mouse Dog"),
c = c("Fruit", "Clothes", "Animals"))
# Appends 'Animals'
df3 <- regex_left_join(df1,df2, c("a" = "b"))
# Appends Nothing
df3 <- stringdist_left_join(df1, df2, by = c("a" = "b"), max_dist = 3, method = "lcs")
我想使用字符串“Apple”、“Sock”和“Mouse Dog”将 df2 的 c 列附加到 df1。
我尝试使用regex_join和blurjoin执行此操作,但字符串的顺序似乎很重要,并且似乎找不到解决方法。
解决方案
regex_left_join
有效,但它不仅仅是在寻找任何相似之处。正如描述中所说,
通过另一个表中的正则表达式列连接具有字符串列的表
所以,我们需要提供一个正则表达式模式。如果df2$b
包含单独的感兴趣的单词,我们可能会这样做
(df2$regex <- gsub(" ", "|", df2$b))
# [1] "Kiwi|Lemon|Apple" "Shirt|Sock|Glove" "Mouse|Dog"
接着
regex_left_join(df1, df2, by = c(a = "regex"))[-ncol(df1) - ncol(df2)]
# A tibble: 3 x 3
# a b c
# <chr> <chr> <chr>
# 1 Apple Pear Orange Kiwi Lemon Apple Fruit
# 2 Sock Shoe Hat Shirt Sock Glove Clothes
# 3 Cat Mouse Dog Mouse Dog Animals
where-ncol(df1) - ncol(df2)
只需删除包含正则表达式模式的最后一列。
推荐阅读
- vb.net - 在 VB 的 Linq 中是否“让”延迟(或延迟评估)?
- regex - 在 Go 中使用正则表达式在边框之间选择文本
- bash - 循环遍历数组并基于一列值,连接另一列值
- react-native - 在安装/卸载时动画视图的动态高度
- lotus-notes - 文档在嵌入视图中不可见
- python - 如何使用 tf.py_func 包装器制作 from_tensor_slice 的嵌套结构以在 Dataset.map 中传递两个参数
- javascript - 有没有办法在 slickgrid 2.4.3 中以编程方式选择一行?
- php - 如何最后从子主题加载css?
- jquery - 使用 jQuery 将 PDF 文件编码为 base64 以通过 JSON 中的 REST API 发送
- c++ - std::shared_ptr 未更新其计数