# How to check if a value exists in an R data frame or not?

There are many small objectives that helps us to achieve a greater objective in data analysis. One such small objective is checking if a value exists in the data set or not. In R, we have many objects for data set such as data frame, matrix, data.table object etc. If we want to check if a value exists in an R data frame then any function can be used.

## Example

Consider the below data frame:

Live Demo

> set.seed(3654)
> x1<-rpois(20,5)
> x2<-rpois(20,8)
> x3<-rpois(20,10)
> x4<-rpois(20,3)
> df1<-data.frame(x1,x2,x3,x4)
> df1

## Output

  x1 x2 x3 x4
1  4  5 16  2
2  5  4 15  2
3  6  6 13  3
4  2  6  7  4
5  5  4  9  4
6  6  8  9  5
7  5  6 12  3
8  4  5  8  7
9  2  9 12  1
10 6  7  6  1
11 3  4  9  3
12 2  5  5  3
13 3  7  7  4
14 4  7  8  2
15 6 12  9  1
16 8  4 15  1
17 5  8 10  4
18 3 12 11  2
19 3  8 12  3
20 8 13 11  1

Checking whether a particular value exists in df1 or not:

> any(df1==4)
 TRUE
> any(df1==5)
 TRUE
> any(df1==20)
 FALSE
> any(df1==8)
 TRUE
> any(df1==15)
 TRUE
> any(df1==12)
 TRUE

Let’s have a look at another example:

## Example

Live Demo

> S1<-sample(LETTERS[1:10],20,replace=TRUE)
> S2<-sample(LETTERS[21:26],20,replace=TRUE)
> df2<-data.frame(S1,S2)
> df2

## Output

  S1 S2
1  G W
2  C V
3  J W
4  E Y
5  H W
6  H V
7  H U
8  C W
9  A W
10 J W
11 J U
12 D V
13 C U
14 J W
15 G U
16 E X
17 D Y
18 B X
19 E U
20 I U

## Example

> any(df2=="A")
 TRUE
> any(df2=="B")
 TRUE
> any(df2=="C")
 TRUE
> any(df2=="c")
 FALSE
> any(df2=="e")
 FALSE
> any(df2=="F")
 FALSE
> any(df2=="J")
 TRUE
> any(df2=="M")
 FALSE
> any(df2=="N")
 FALSE