Mohammad
Mohammad

Reputation: 1098

How to find the first missing number in each gap of consequent numbers?

I have a series of numbers between 1 to 10 in ascending order which some numbers are missing. I want to find the first number for each missing gap. I'm doing this in R. For example:

numbers=c(1,2,5,6,7,10)

the numbers missing are 3,4 and 8,9 so I want to find 3 and 8:

3
8 

any suggestions? thanks

Upvotes: 1

Views: 82

Answers (1)

lmo
lmo

Reputation: 38510

You can accomplish this using diff and subsetting as follows

numbers[diff(numbers) != 1] + 1
[1] 3 8

diff(numbers) != 1 will return a logical vector where adjacent elements are not equal to the next number in the "counting" order. numbers[] will subset these, then add 1 to return the missing values.

Upvotes: 2

Related Questions