Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can find missing numbers in consecutive numbers?

Tags:

r

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 ?

like image 942
Boram Lim Avatar asked Apr 15 '15 04:04

Boram Lim


People also ask

How do you find a missing number in multiple numbers?

To find the multiple missing elements run a loop inside it and see if the diff is less than arr[i] – i then print the missing element i.e., i + diff. Now increment the diff as the difference is increased now. Repeat from step 2 until all the missing numbers are not found.


2 Answers

The simplest solution would be

> setdiff(1:7, df$y)
[1] 3 5 6
like image 183
vonjd Avatar answered Oct 03 '22 15:10

vonjd


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
like image 38
asbebe Avatar answered Oct 03 '22 16:10

asbebe