我使用下面的代码创建一个矩阵,该矩阵比较一个向量中的所有字符串,以查看它们是否包含第二个向量中的任何模式:
strngs <- c("hello there", "welcome", "how are you")
pattern <- c("h", "e", "o")
M <- matrix(nrow = length(strngs), ncol = length(pattern))
for(i in 1:length(strngs)){
for(j in 1:length(pattern)){
M[i, j]<-str_count(strngs[i], pattern[j])
}
}
M
它工作得很好,并返回我正在寻找的矩阵:
[,1] [,2] [,3]
[1,] 2 3 1
[2,] 0 2 1
[3,] 1 1 2
但是,我的真实数据集很大,这样的循环不能很好地扩展到具有 117、746、754 个值的矩阵。有谁知道我可以对其进行矢量化或以其他方式加速的方法吗?或者我应该只学习C++? ;)
谢谢!
最佳答案
您可以按照 @snoram 的建议使用 outer
和 stri_count_fixed
。
outer(strngs, pattern, stringi::stri_count_fixed)
# [,1] [,2] [,3]
#[1,] 2 3 1
#[2,] 0 2 1
#[3,] 1 1 2
关于r - R 匹配字符串模式中矩阵运算的向量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53046383/