How to Use NOT IN Operator in R with Examples

Like database you have option to use like NOT IN operator in R. In this tutorial I will show how to use NOT IN operator in R with example. To understand NOT IN functionality let’s create two vectors and one data frame first.
#define vector of character data
character_vector<-c(‘Minhaj’, ‘Rahman’, ‘Khan’, ‘Fahim’, ‘Karim’, ‘Rahim’, ‘Zabir’)
#define vector of numeric data
numeric_vector<-c(88, 85, 81, 83, 75, 74, 99)
#define a data frame
df <- data.frame(
id=c(1,2,3,4,5,6,7)
name=c(‘Minhaj’, ‘Rahman’, ‘Khan’, ‘Fahim’, ‘Karim’, ‘Rahim’, ‘Zabir’),
math_score=c(88, 85, 81, 83, 75, 74, 99))
Here is the basic syntax to select all elements that are not in a list of values in R:
!(data %in% c(value1, value2, value3, ...))

In the following examples I will show how to use this syntax in different examples.

Example 1: How to Use “NOT IN” with Vectors

The following code shows how to select all values in a vector in R that are not in a certain list of numeric values:

#display all values in vector not equal to 99 or 74
numeric_vector[!(numeric_vector%in% c(99, 74))]

[1] 88 85 81 83 75

The following code shows how to select all values in a vector in R that are not in a certain list of character values:

#display all elements in vector not equal to 'Zabir', or 'Rahim'
character_vector[!(character_vector %in% c('Zabir', 'Rahim'))]

[1] "Minhaj" "Rahman" "Khan" "Fahim" "Karim"

Example 2: How to Use “NOT IN” with Data Frames

#view data frame
df
id name math_score
1 1 Minhaj 88
2 2 Rahman 85
3 3 Khan 81
4 4 Fahim 83
5 5 Karim 75
6 6 Rahim 74
7 7 Zabir 99

The following code shows how to select all rows in a data frame in R in which a certain column is not equal to certain numeric values:

#select all rows where team is not equal to 74 or 99
subset(df, !(math_score%in% c(74, 99)))

id name math_score
1 1 Minhaj 88
2 2 Rahman 85
3 3 Khan 81
4 4 Fahim 83
5 5 Karim 75

The following code shows how to select all rows in a data frame in R in which a certain column is not equal to certain character values:

#select all rows where name is not equal to 'Zabir' or 'Rahim' 
subset(df, !(name %in% c('Zabir', 'Rahim'))) 

id name math_score
1 1 Minhaj 88
2 2 Rahman 85
3 3 Khan 81
4 4 Fahim 83
5 5 Karim 75

In this tutorial, I have shown how to use NOT IN operator in R programming. Hope, you will enjoy this tutorial. In addition, you can subscribe to our facebook page https://www.facebook.com/LearningBigDataAnalytics to get updated on new posts.

Add a Comment