Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 785
Mike Avatar asked Oct 28 '14 08:10

Mike


People also ask

How do you find the first element of an array that is not consecutive?

Find the first non-consecutive number in an array Your task is to find the first element of an array that is not consecutive. E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number.

How do you know if an array is sequential?

Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.


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
like image 148
akrun Avatar answered Sep 29 '22 15:09

akrun


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
like image 35
Carl Witthoft Avatar answered Sep 29 '22 17:09

Carl Witthoft


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
like image 20
Alex Avatar answered Sep 29 '22 15:09

Alex