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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With