TarJae
TarJae

Reputation: 79246

How to identify each integer sequence regardless of ties in a vector

This question is related to this identify whenever values repeat in r

While searching for answer there this new question arose:

I have this vector:

vector <- c(1, 1, 2, 3, 5, 6, 6, 7, 1, 1, 1, 1, 2, 3, 3)

I would like to identify each consecutive (by 1) integer sequence e.g. 1,2,3,.. or 3,4,5,.. or 4,5,6,7,...

BUT It should allow ties 1,1,2,3,.. or 3,3,4,5,... or 4,5,5,6,6,7

The expected output would be a list like:

sequence1 <- c(1, 1, 2, 3)
sequence2 <- c(5, 6, 6, 7)
sequence3 <- c(1, 1, 1, 1, 2, 3, 3)

So far the nearest approach I found here Check whether vector in R is sequential?, but could not transfer it to what I want.

Upvotes: 2

Views: 43

Answers (1)

akrun
akrun

Reputation: 887881

An option is with diff and cumsum

split(vector, cumsum(c(TRUE, abs(diff(vector)) > 1)))

-output

`1`
[1] 1 1 2 3

$`2`
[1] 5 6 6 7

$`3`
[1] 1 1 1 1 2 3 3

Upvotes: 2

Related Questions