我想找到更好的方法来找到我正在比较的两个字符串的更大的nchar。
假设我在 sentenceMatch 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, ]))
}
}
有没有更好的解决方案如何才能加快计算速度?非常感谢您对前进的任何帮助。
答案 0 :(得分:9)
使用outer
:
nc <- nchar(sentenceMatch[[1]])
outer(nc, nc, pmax)
,并提供:
[,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
答案 1 :(得分:4)
sentences <- c("hello how are you",
"hello how are you friend",
"im fine and how about you",
"good thanks",
"great to hear that")
sn <- nchar(sentences)
n <- length(sn)
M1 <- matrix(sn, n, n)
M2 <- t(M1)
(M1 + M2 + abs(M1 - M2)) / 2
# [,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
我使用的事实是max(x,y)=(x + y + abs(x-y))/ 2.性能非常相似:
set.seed(1)
sentences <- replicate(paste0(rep("a", rpois(1, 3000)), collapse = ""), n = 1000)
f1 <- function(sentences) {
sn <- nchar(sentences)
n <- length(sn)
M1 <- matrix(sn, n, n)
M2 <- t(M1)
(M1 + M2 + abs(M1 - M2)) / 2
}
f2 <- function(sentences) {
nc <- nchar(sentences)
outer(nc, nc, pmax)
}
library(microbenchmark)
microbenchmark(f1(sentences), f2(sentences))
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# f1(sentences) 33.39924 37.66673 57.9912 42.45684 82.01905 122.5075 100 b
# f2(sentences) 31.59887 34.97866 50.5065 37.82217 77.82042 103.6342 100 a