我有一个字符向量,并且想要为每对向量值(使用stringdist
包)创建一个包含距离矩阵的矩阵。目前,我有嵌套的for循环的实现:优化R中for循环的性能
library(stringdist)
strings <- c("Hello", "Helo", "Hole", "Apple", "Ape", "New", "Old", "System", "Systemic")
m <- matrix(nrow = length(strings), ncol = length(strings))
colnames(m) <- strings
rownames(m) <- strings
for (i in 1:nrow(m)) {
for (j in 1:ncol(m)) {
m[i,j] <- stringdist::stringdist(tolower(rownames(m)[i]), tolower(colnames(m)[j]), method = "lv")
}
}
导致下面的矩阵:
> m
Hello Helo Hole Apple Ape New Old System Systemic
Hello 0 1 3 4 5 4 4 6 7
Helo 1 0 2 4 4 3 3 6 7
Hole 3 2 0 3 3 4 2 5 7
Apple 4 4 3 0 2 5 4 5 7
Ape 5 4 3 2 0 3 3 5 7
New 4 3 4 5 3 0 3 5 7
Old 4 3 2 4 3 3 0 6 8
System 6 6 5 5 5 5 6 0 2
Systemic 7 7 7 7 7 7 8 2 0
但是,如果我有 - 例如 - lenght 1000的矢量与许多非独特的价值观,这个矩阵是相当大的(比方说,800行800列)和循环是非常慢。我喜欢优化性能,例如通过使用apply
函数,但我不知道如何将上面的代码翻译成apply
语法。谁能帮忙?
'apply'也循环,并不见得快于for循环。请参阅http://stackoverflow.com/questions/2275896/is-rs-apply-family-more-than-syntactic-sugar – 2014-09-03 12:04:08
代码优化问题应该在CodeReview上提出,而不是StackOverflow http://codereview.stackexchange.com/ – 2016-06-26 16:08:41