R: How to find unclassified elements in an array

I have an array with multiple numbers in it and I don't know in advance what the numbers will be. I would like to highlight those numbers in an array that 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 can be of variable length, including zero length

thank

+3


source to share


3 answers


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

      

+8


source


Oddly enough :-), I can offer one of my creations: cgwtools:seqle

. seqle

works the same as rle

, but returns sequences, not repetitions.



 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

      

+4


source


You can use a function lag

from the 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

      

+2


source







All Articles