1

I have a vector of integers with 'discountinuities' and I would like to convert in a list of vectors with consecutive values

Example

vec = c(1,2,5,7,8,9,11,12,13,15)
[1]  1  2  5  7  8  9 11 12 13 15

Expected output:

[[1]]
[1] 1 2

[[2]]
[1] 5

[[3]]
[1] 7 8 9

[[4]]
[1] 11 12 13

[[5]]
[1] 15

Is there any simple way to do this?

K.Hua
  • 769
  • 4
  • 20

1 Answers1

1

An option is to split by creating a grouping variable created by checking the difference of adjacent elements

split(vec, cumsum(c(TRUE, diff(vec) != 1)))
#$`1`
#[1] 1 2

#$`2`
#[1] 5

#$`3`
#[1] 7 8 9

#$`4`
#[1] 11 12 13

#$`5`
#[1] 15
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    That was exactly what I was looking for ! Thanks ! i will accept the answer when stackoverflow will allow me to – K.Hua Oct 08 '19 at 18:32