我想找到更好的方法来找到我正在相互比较的两个字符串的更大的 nchar 。
假设我有字符串句子匹配data.frame 和我需要创建一个 max(nchar(string1), nchar(string2)) 矩阵,但没有 for 循环,这是非常慢的方法。
sentenceMatch <- data.frame(Sentence=c("hello how are you",
"hello how are you friend",
"im fine and how about you",
"good thanks",
"great to hear that"))
sentenceMatch$Sentence <- as.character(sentenceMatch$Sentence)
overallMatrix_nchar <- matrix(, nrow = dim(sentenceMatch)[1], ncol = dim(sentenceMatch)[1])
for (k in 1:dim(sentenceMatch)[1]) {
for (l in 1:dim(sentenceMatch)[1]) {
overallMatrix_nchar[k, l] <- max(nchar(sentenceMatch[k, ]), nchar(sentenceMatch[l, ]))
}
}
有没有更好的解决方案如何加快计算速度?非常感谢您在转发中提供的任何帮助。
Use outer
:
nc <- nchar(sentenceMatch[[1]])
outer(nc, nc, pmax)
giving:
[,1] [,2] [,3] [,4] [,5]
[1,] 17 24 25 17 18
[2,] 24 24 25 24 24
[3,] 25 25 25 25 25
[4,] 17 24 25 11 18
[5,] 18 24 25 18 18
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)