首页 > 解决方案 > 通过字符串匹配从其他数据帧中查找特定值

问题描述

我在下面提到了两个数据框:

DF1

ID     Value
AL-1   Adf "& ert
AL-2   new '? rti
AL-3   oll- drt/
AL-4   plr -rte-

DF2

Value        Type           
Adf & ert    AA
new  rti     AA
oll-drt&     AB
plr-rte      AC

所需输出:

ID     Value         Type
AL-1   Adf "& ert    AA
AL-2   new '? rti    AA
AL-3   oll- drt/     AB
AL-4   plr -rte-     AC

我想将 Value 列中 DF1 的字符与 DF2 Value 列的字符进行匹配,并导出Type.

尝试使用 phonics 库但还没有完成,这里需要一些建议。

标签: rdataframedplyrtidyr

解决方案


您可以使用该adist函数来获取df1$Valuedf2$Value. 然后您可以选择距离最短的那个(因此将优先考虑完全匹配):

library(utils)
df1$Type <- df2$Type[apply(adist(df1$Value, df2$Value), 1, which.min)]

df1
#    ID      Value Type
#1 AL-1 Adf "& ert   AA
#2 AL-2 new '? rti   AA
#3 AL-3  oll- drt/   AB
#4 AL-4  plr -rte-   AC

推荐阅读