我正在尝试为基于自定义距离函数的字符串创建一个距离矩阵(用于聚类)。我在一个 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
and j in k:n
。我想知道是否还有其他可以优化的东西。