R中的快速字符串匹配

ale*_*rab 8 string r

我试图在大型数据集中进行单词匹配.我想知道是否有办法加快我工作流程中最慢的操作.

我的目的是找到单词词典和单词向量列表之间匹配的位置.

words <- c("cat", "dog", "snake", "cow")
scores <- c(1.5, 0.7, 3.5, 4.6)
dic <- data.frame(words, scores)

wordList <- list(c("jiraffe", "dog"), c("cat", "elephant"), c("snake", "cow"))
Run Code Online (Sandbox Code Playgroud)

到目前为止我发现的最快的方法是这样做:

matches <- function(wordList) {
    subD <- which(dic$words %in% wordList)
}
Run Code Online (Sandbox Code Playgroud)

我想要的输出是:

matches(wordList):
list(c(2), c(1), c(3, 4))
Run Code Online (Sandbox Code Playgroud)

我可以稍后用它来获得每个wordList单元的平均分数

averageScore <- sapply(matches, function(x) {mean(dic[x, "scores"]})
Run Code Online (Sandbox Code Playgroud)

有没有比我在函数中做的更快的方式进行字符串匹配:

subD <- which(dic$words %in% wordList)
Run Code Online (Sandbox Code Playgroud)

我尝试了dplyr方式,认为它可能更快,使用第一个"过滤器"来获取"dic"的子集并在其上应用"colMeans",但它似乎是两倍慢.

此外,在循环中运行我的匹配函数与在其上使用"lapply"一样慢.

我错过了什么吗?有没有比两者都快的方法?

Jos*_*ien 9

这是一个选项:

library(data.table)
nn <- lengths(wordList)  ## Or, for < R-3.2.0, `nn <- sapply(wordList, length)` 
dt <- data.table(grp=rep(seq_along(nn), times=nn), X = unlist(wordList), key="grp")
dt[,Score:=scores[chmatch(X,words)]]
dt[!is.na(Score), list(avgScore=mean(Score)), by="grp"]
#    grp avgScore
# 1:   1     0.70
# 2:   2     1.50
# 3:   3     4.05
Run Code Online (Sandbox Code Playgroud)