计算字符串中连续字母的最大值 [英] Count the maximum of consecutive letters in a string
本文介绍了计算字符串中连续字母的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个向量:
vector <- c("XXXX-X-X", "---X-X-X", "--X---XX", "--X-X--X", "-X---XX-", "-X--X--X", "X-----XX", "X----X-X", "X---XX--", "XX--X---", "---X-XXX", "--X-XX-X")
我想检测出现 X 的连续次数的最大值.所以,我的预期向量是:
I want to detect the maximum of consecutive times that appears X. So, my expected vector would be:
4, 1, 2, 1,2, 1, 2, 1, 2, 2, 3, 2
推荐答案
在基础 R 中,我们可以将每个 vector
拆分为单独的字符,然后使用 rle
找到 <代码>最大X"的连续长度.
In base R, we can split each vector
into separate characters and then using rle
find the max
consecutive length for "X".
sapply(strsplit(vector, ""), function(x) {
inds = rle(x)
max(inds$lengths[inds$values == "X"])
})
#[1] 4 1 2 1 2 1 2 1 2 2 3 2
这篇关于计算字符串中连续字母的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文