2

If I have a numeric vector [1 2 3 4 7 8 9 10 15 16 17], how can I split it so that I have multiple vectors returned that separate the continuous elements of that vector? I.e. [1 2 3 4] [7 8 9 10] [15 16 17]. I've found an answer of how to do this in matlab, but I only use R.

Thanks.

user2728808
  • 560
  • 3
  • 18
  • Some alternatives here: http://stackoverflow.com/questions/8400901/detect-intervals-of-the-consequent-integer-sequences – Henrik Aug 29 '13 at 10:41

2 Answers2

6

Here's another alternative:

vec <- c( 1, 2, 3, 4, 7, 8, 9, 10, 15, 16, 17 )
split(vec, cumsum(seq_along(vec) %in% (which(diff(vec)>1)+1)))
# $`0`
# [1] 1 2 3 4
# 
# $`1`
# [1]  7  8  9 10
# 
# $`2`
# [1] 15 16 17
alexwhan
  • 15,636
  • 5
  • 52
  • 66
0

Another option:

split(vec, cummax(c(1,diff(vec))))

Result

$`1`
[1] 1 2 3 4

$`3`
[1]  7  8  9 10

$`5`
[1] 15 16 17
Ferdinand.kraft
  • 12,579
  • 10
  • 47
  • 69