【发布时间】:2015-09-02 08:45:50
【问题描述】:
我正在尝试根据自定义距离函数为字符串创建一个距离矩阵(用于聚类)。我在 6000 个单词的列表上运行了代码,并且自上 90 分钟以来它仍在运行。我有 8 GB RAM 和 Intel-i5,所以问题仅出在代码上。 这是我的代码:
library(stringdist)
#Calculate distance between two monograms/bigrams
stringdist2 <- function(word1, word2)
{
#for bigrams - phrases with two words
if (grepl(" ",word1)==TRUE) {
#"Hello World" and "World Hello" are not so different for me
d=min(stringdist(word1, word2),
stringdist(word1, gsub(word2,
pattern = "(.*) (.*)",
repl="\\2,\\1")))
}
#for monograms(words)
else{
#add penalty of 5 points if first character is not same
#brave and crave are more different than brave and bravery
d=ifelse(substr(word1,1,1)==substr(word2,1,1),
stringdist(word1,word2),
stringdist(word1,word2)+5)
}
d
}
#create distance matrix
stringdistmat2 = function(arr)
{
mat = matrix(nrow = length(arr), ncol= length(arr))
for (k in 1:(length(arr)-1))
{
for (j in k:(length(arr)-1))
{
mat[j+1,k] = stringdist2(arr[k],arr[j+1])
}
}
as.dist(mat)
}
test = c("Hello World","World Hello", "Hello Word", "Cello Word")
mydmat = stringdistmat2(test)
> mydmat
1 2 3
2 1
3 1 2
4 2 3 1
我认为问题可能是我使用循环而不是应用 - 但后来我发现在许多地方循环并不是那么低效。更重要的是,我不够熟练,无法使用 apply 我的循环是嵌套循环,例如 k in 1:n 和 j in k:n。我想知道是否还有其他可以优化的东西。
【问题讨论】:
-
在 R 屏幕上等待似乎不对,所以我又打开了一个 R 控制台并尝试了这个:
arr1 = c("Hello World","World Hello", "Hello Word", "Cello Word") mytest = function(arr1){as.dist(sapply(arr1,stringdist,b=arr1))} mytest(arr1)它给了我想要的距离矩阵。现在我想知道如何更改我的函数以使其适用于向量
标签: r string performance levenshtein-distance edit-distance