Mark
Mark

Reputation: 1769

How to find missing numbers in a sequence?

I have a vector containing a list of numbers. How do I find numbers that are missing from the vector?

For example:

sequence <- c(12:17,1:4,6:10,19)

The missing numbers are 5, 11 and 18.

Upvotes: 3

Views: 3131

Answers (4)

VFreguglia
VFreguglia

Reputation: 2311

You can use the setdiff() function to compute set differences. You want the difference between the complete sequence (from min(sequence) to max(sequence)) and the sequence with missing values.

setdiff(min(sequence):max(sequence), sequence)

Upvotes: 5

Len Greski
Len Greski

Reputation: 10855

sequence <- c(12:17,1:4,6:10,19)

seq2 <- min(sequence):max(sequence)

seq2[!seq2 %in% sequence]

...and the output:

> seq2[!seq2 %in% sequence]
[1]  5 11 18
> 

Upvotes: 9

iod
iod

Reputation: 7592

c(1:max(sequence))[!duplicated(c(sequence,1:max(sequence)))[-(1:length(sequence))]]
[1]  5 11 18

Not a particularly elegant solution, I admit, but what it does is determines which in the vector 1:max(sequence) are duplicates of sequence, and then selects those out of that same vector.

Upvotes: 1

G5W
G5W

Reputation: 37641

This answer just gets all of the numbers from the lowest to highest in the sequence, then asks which are not present in the original sequence.

which(!(seq(min(sequence), max(sequence)) %in% sequence))
[1]  5 11 18

Upvotes: 2

Related Questions