2

I've a big vector of 200,000 objects. The vector contains integers values. And the vector is sorted. How can I split the vector in chunk of adjacent points.

Example :

x <- c(1,4,5,6,8,9,20,21,30)

Will give me (here a R list as a result) :

[[1]]
[1] 1

[[2]]
[1] 4 5 6

[[3]]
[1] 8 9

[[4]]
[1] 20 21

[[5]]
[1] 30

The basic way would be to loop across the values but it's not very efficient. Any ideas ?

ekad
  • 14,436
  • 26
  • 44
  • 46
Nicolas Rosewick
  • 1,938
  • 4
  • 24
  • 42

1 Answers1

1

We can use diff with cumsum to create a grouping variable and split the vector

unname(split(x, cumsum(c(TRUE, diff(x)!=1))))
#[[1]]
#[1] 1

#[[2]]
#[1] 4 5 6

#[[3]]
#[1] 8 9

#[[4]]
#[1] 20 21

#[[5]]
#[1] 30
akrun
  • 874,273
  • 37
  • 540
  • 662