加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – R中的计数模式匹配

发布时间:2020-12-14 06:26:40 所属栏目:百科 来源:网络整理
导读:如何有效地计算在另一个字符串中出现的一个字符串的实例数? 以下是我迄今为止的代码.它成功识别是否在另一个字符串中出现了一个字符串的任何实例.但是,我不知道如何将它从TRUE / FALSE关系扩展到计数关系. x - ("Hello my name is Christopher. Some people
如何有效地计算在另一个字符串中出现的一个字符串的实例数?

以下是我迄今为止的代码.它成功识别是否在另一个字符串中出现了一个字符串的任何实例.但是,我不知道如何将它从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]中出现两次,我希望mmm [1,1]为2而不是1.

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

两个快速提示:

>避免双重for循环,你不需要它;)
>使用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,string=lll)
#      chris hell
# [1,]     2    1
# [2,]     1    0
# [3,]     0    0

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读