R中的计数模式匹配

Chr*_*ris 5 regex r pattern-matching

如何有效地计算在另一个字符串中出现的一个字符串的实例数?

以下是我迄今为止的代码.它成功识别是否在另一个字符串中出现了一个字符串的任何实例.但是,我不知道如何将它从TRUE/FALSE关系扩展到计数关系.

x <- ("Hello my name is Christopher. Some people call me Chris")
y <- ("Chris is an interesting person to be around")
z <- ("Because he plays sports and likes statistics")

lll <- tolower(list(x,y,z))
dict <- tolower(c("Chris", "Hell"))

mmm <- matrix(nrow=length(lll), ncol=length(dict), NA)

for (i in 1:length(lll)) {
for (j in 1:length(dict)) {
    mmm[i,j] <- sum(grepl(dict[j],lll[i]))
}
}
mmm
Run Code Online (Sandbox Code Playgroud)

它产生:

       [,1] [,2]
 [1,]    1    1
 [2,]    1    0
 [3,]    0    0
Run Code Online (Sandbox Code Playgroud)

由于小写字符串"chris"出现两次,lll[1]我希望mmm[1,1]是2而不是1.

真实的例子是更高的维度...所以如果代码可以被矢量化而不是使用我的强力循环,那就太喜欢了.

Ric*_*rta 7

两个快速提示:

  1. 避免双重for循环,你不需要它;)
  2. 使用stringr

library(stringr)

dict <- setNames(nm=dict)  # simply for neatness
lapply(dict, str_count, string=lll)
# $chris
# [1] 2 1 0
#
# $hell
# [1] 1 0 0
Run Code Online (Sandbox Code Playgroud)

或者作为矩阵:

#  sapply(dict, str_count, string=lll)
#      chris hell
# [1,]     2    1
# [2,]     1    0
# [3,]     0    0
Run Code Online (Sandbox Code Playgroud)

  • 这将取决于您对"有效"的定义.看看`microbenchmark`包.请注意,`stringr`是语法糖,以便更容易使用字符串.自己编码将始终如此快或更快. (2认同)