一个人如何有效地计算一个字符串在另一字符串中出现的实例数?
以下是我到目前为止的代码。它成功识别一个字符串中的任何实例是否出现在另一字符串中。但是,我不知道如何将其从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
它产生:
[,1] [,2]
[1,] 1 1
[2,] 1 0
[3,] 0 0
由于小写字符串“ chris”在lll[1]
I中出现了两次,因此我想mmm[1,1]
成为2而不是1。
真正的例子是更高的维度...如果可以对代码进行矢量化而不是使用我的蛮力进行循环,那将是很乐意的。
两个快速提示:
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
# sapply(dict, str_count, string=lll)
# chris hell
# [1,] 2 1
# [2,] 1 0
# [3,] 0 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句