How to check whether a particular word exists in an R data frame column?


If we have a character column in an R data frame then we might want to check whether a particular value exist in the column or not. For example, if we have a gender column then we might want to check whether transgender exists in that column or not. This can be done with the help of grepl function. Check out the below examples to understand how it works.

Consider the below data frame −

Example

 Live Demo

x<-sample(c("Mazda","Merc","Fiat"),20,replace=TRUE)
df1<-data.frame(x)
df1

Output

   x
1  Fiat
2  Merc
3  Fiat
4  Merc
5  Merc
6  Fiat
7  Fiat
8  Fiat
9  Mazda
10 Fiat
11 Mazda
12 Mazda
13 Fiat
14 Fiat
15 Mazda
16 Mazda
17 Merc
18 Merc
19 Mazda
20 Merc

Checking whether Merc exists in the column x of df1 −

Example

grepl("Merc",df1$x)

Output

[1]  FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE TRUE TRUE FALSE TRUE

Example

 Live Demo

y<-sample(c("Hotel","Motel","Restaurant"),20,replace=TRUE)
df2<-data.frame(y)
df2

Output

   y
1  Motel
2  Hotel
3  Motel
4  Motel
5  Hotel
6  Hotel
7  Motel
8  Motel
9  Hotel
10 Hotel
11 Restaurant
12 Restaurant
13 Motel
14 Hotel
15 Motel
16 Hotel
17 Hotel
18 Restaurant
19 Hotel
20 Hotel

Checking whether Motel exists in the column y of df2 −

Example

grepl("Motel",df2$y)

Output

[1] TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE
[13] TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE

Updated on: 10-Feb-2021

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements