Mohammad Mohammad - 1 year ago 85
R Question

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:


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


any suggestions? thanks

lmo lmo
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download