Boram Lim
Boram Lim

Reputation: 323

How I can find missing numbers in consecutive numbers?

I have a data as below

ID   x    y 
1    0    1 
2    0    1
3    0    2
4    0    2
5    1    4
6    10   7
7    10   7

Y variable ranges from 1 to 7 and we can find 3,5,6 are missing in Y variable. How I can find missing numbers in consecutive numbers ?

Upvotes: 5

Views: 4199

Answers (3)

Vin
Vin

Reputation: 151

You can also try below logic to find the missing value,

val <- 400
num <- c(0:49,51:100)
if(any(val == num)){
  cat(val, "is present in the data")
}else{
  cat(val, "is missing in the data")
}

Upvotes: 0

vonjd
vonjd

Reputation: 4380

The simplest solution would be

> setdiff(1:7, df$y)
[1] 3 5 6

Upvotes: 10

asbebe
asbebe

Reputation: 71

Here is the data frame you give.

id = rep(1:7)
x = c(0,0,0,0,1,10,10)
y = c(1,1,2,2,4,7,7)

df = data.frame(id,x,y)

This is the way to find missing values from 1 to 7 in df$y. Figuring out unique values in df$y, and checking there is not unique values of df$y in rep(1:7) which is consecutive numbers from 1 to 7.

rep(1:7)[!(rep(1:7) %in%  unique(df$y))]
[1] 3 5 6

Upvotes: 1

Related Questions