获取R中两个数据帧的近似子串的位置

时间:2015-08-26 15:52:03

标签: r pattern-matching fuzzy-search

我有两个数据框。第一个(word.library)包括应该匹配第二个数据框(targetframe)中的字符串的字符串。

word.library <- data.frame(mainword = c("important word",
                                                "crazy sayings"))    

tragetframe <- data.frame(words= c("Important Words",
                                           "I would also Importante worde of thes substring",
                                           "No mention of this crazy sayingsys"))

我只想出了逐个解决方案(循环也是如此),但这并不能满足我的需求:

positions <- aregexec(word.library[1,1], tragetframe$words, max.distance = 0.1)

positions <- aregexec(word.library[2,1], tragetframe$words, max.distance = 0.1)

最后:我正在寻找一个解决方案,立即对列word.library$mainword中的所有字符串执行此操作。有谁有个好主意?谢谢。

1 个答案:

答案 0 :(得分:1)

find <- function(library.vec, frame.vec) {
  aregexec(library.vec, frame.vec, max.distance = 0.1)
}

如果从您尝试的表达式创建了一个函数,您将能够将它包含在apply family函数中以重复单词库。

mapply(find, word.library[,1], list(tragetframe[,1]))
#     [,1] [,2]
#[1,] 1    -1  
#[2,] 14   -1  
#[3,] -1   20 

在此过程中删除属性。每个字的输出按列排列。如果你想保留属性,请尝试:

lapply(word.library[,1], find, tragetframe[,1])