5

I have an array with several numbers in it and I don't know beforehand what the numbers will be. I would like to separate out those numbers in the array which are not sequential to the previous number (in addition to the first number in the sequence).

For example: Array: 2 3 4 5 10 11 12 15 18 19 20 23 24

I would like to return 2 10 15 18 23

The original array could be of variable length, including length zero

Thanks

Mike
  • 1,049
  • 5
  • 20
  • 46

3 Answers3

11

Try

 v1 <- c(2:5,10:12,15, 18:20, 23:24)
 v1[c(TRUE,diff(v1)!=1)]
#[1]  2 10 15 18 23

Update

If you want to get the last sequential number, try

v1[c(diff(v1)!=1, TRUE)]
#[1]  5 12 15 20 24
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks for the answer. Quick question: if possible, how could I alter the above code to select the last sequential number i.e. instead of '2 10 15 18 23', select instead '5 12 15 20 24'? Thanks again! – Mike Oct 28 '14 at 09:02
  • 1
    We all reinvent the wheel, don't we :-( . (See my self-promotion of `seqle`) Note BTW that you could replace `!=1` with `!=0` to simulate `rle`, or `!=N` for any other stepped-sequence. – Carl Witthoft Oct 28 '14 at 11:34
5

Oddly enough :-), I get to proffer one of my creations: cgwtools:seqle . seqle works just like rle but returns sequence runs rather than repetition runs.

 foo<- c(2,3,4,5,10,11,12,15,18,19,20,23,24)
 seqle(foo)
Run Length Encoding
  lengths: int [1:5] 4 3 1 3 2
  values : num [1:5] 2 10 15 18 23
Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
2

You can use function lag from package dplyr:

arr <- c(2, 3, 4, 5, 10, 11, 12, 15, 18, 19, 20, 23, 24)

index_not_sequential <- which(arr - dplyr::lag(arr, 1, default=-1 ) != 1)

arr[index_not_sequential]

gives

[1]  2 10 15 18 23
Alex
  • 15,186
  • 15
  • 73
  • 127
  • You either have dplyr version less than about zero or something is horribly wrong. Or you typed "Lag" instead of "lag". But I think you transcribed that error message rather than cut n paste it... So... weird... – Spacedman Oct 28 '14 at 08:53
  • Yeah it is weird, as I can definitely use other objects from the dplyr package. Yes, I transcribed the message. Thanks for the help though! – Mike Oct 28 '14 at 09:03