Search code examples
arraysrsequential

R: How to find non-sequential elements in an array


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


Solution

  • 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