Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R语言中的快速字符串匹配_R_String - Fatal编程技术网

R语言中的快速字符串匹配

R语言中的快速字符串匹配,r,string,R,String,我正在尝试在一个大数据集中进行单词匹配。我想知道是否有办法加快我工作流程中最慢的操作 我的目标是找到单词词典和单词向量列表之间匹配的位置 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(

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

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

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"))
稍后我可以使用它通过执行以下操作来获得每个单词列表单元格的平均分数

averageScore <- sapply(matches, function(x) {mean(dic[x, "scores"]})
averageScore这里有一个选项:

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
库(data.table)

nn有用于快速匹配的包,如
fastmatch
;以及
data.table
包中的
chmatch
函数。也许,这些性能比我们在几行基本R中所能获得的任何性能都要好。是否有绝对要求您使用要匹配的词向量列表的数据结构?在调用sapply()时使用的for循环结构中会出现减速。我将通过构造一个长格式的数据结构来对这个操作进行矢量化,然后您可以使用dplyr之类的工具轻松地对其进行总结。如果你愿意,我可以用这种结构起草一个答案。要扩展Forrest的评论,你可以从一个列表开始(这便于输入组,然后交替转换为
mydf,
ww,如果你的数据确实很大(不适合RAM)那么你无论如何都不应该使用R。如果你要匹配很多次,那么你应该使用btree。谢谢你,Josh,这个解决方案很优雅,比我的解决方案快得多!
averageScore <- sapply(matches, function(x) {mean(dic[x, "scores"]})
subD <- which(dic$words %in% wordList)
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