我正在尝试基于自定义的距离函数为字符串创建距离矩阵(用于聚类)。我在一个包含6000个单词的列表上运行代码,但已经运行了90分钟,并且仍在运行。我的电脑配置是8GB 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函数,但是我发现在许多情况下,循环并不那么低效。更重要的是,我没有足够的技能来将我的循环改写为嵌套的apply函数,例如k in 1:n
和j in k:n
。我想知道是否还有其他可以进行优化的方法。
arr1 = c("Hello World","World Hello", "Hello Word", "Cello Word") mytest = function(arr1){as.dist(sapply(arr1,stringdist,b=arr1))} mytest(arr1)
它给了我想要的距离矩阵。现在我想知道如何更改我的函数,使其适用于向量。 - Gaurav Singhal