Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the maximum of consecutive letters in a string

I have this vector:

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")

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
like image 434
Paula Avatar asked Jan 28 '23 02:01

Paula


1 Answers

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
like image 137
Ronak Shah Avatar answered Feb 07 '23 18:02

Ronak Shah