计算字符串中模式匹配的数量 [英] Count the number of pattern matches in a string
本文介绍了计算字符串中模式匹配的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一个字符串
"AAAAAAACGAAAAAACGAAADGCGEDCG"
我想统计"CG"
重复了多少次.我该怎么做?
I want to count how many times "CG"
is repeated.
How do I do that?
推荐答案
你可以使用gregexpr
来查找vec
中"CG"
的位置代码>.我们必须检查是否没有匹配(-1
).函数 sum
计算匹配的数量.
You can use gregexpr
to find the positions of "CG"
in vec
. We have to check whether there was no match (-1
). The function sum
counts the number of matches.
> vec <- "AAAAAAACGAAAAAACGAAADGCGEDCG"
> sum(gregexpr("CG", vec)[[1]] != -1)
[1] 4
如果你有一个字符串向量,你可以使用sapply
:
If you have a vector of strings, you can use sapply
:
> vec <- c("ACACACACA", "GGAGGAGGAG", "AACAACAACAAC", "GGCCCGCCGC", "TTTTGTT", "AGAGAGA")
> sapply(gregexpr("CG", vec), function(x) sum(x != -1))
[1] 0 0 0 2 0 0
如果你有一个字符串列表,你可以使用 unlist(vec)
然后使用上面的解决方案.
If you have a list of strings, you can use unlist(vec)
and then use the solution above.
这篇关于计算字符串中模式匹配的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文