!(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