How to find the opposite of %in% in R?


To find the opposite of %in%, we can use negation operator ! (exclamation sign). For example, if we have a data frame df that contains a column say x then to subset df by excluding some values (say 2, 3) we can use the command subset(df,!(x %in% c(2,3))).

Example1

Consider the below data frame −

 Live Demo

x1<-rpois(20,5)
y1<-rpois(20,5)
df1<-data.frame(x1,y1)
df1

Output

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

Subsetting df1 by using the opposite of %in% −

subset(df1,!(x1 %in% c(7,6,4)))

   x1 y1
1  5  2
2  5  8
6  5  3
7  3  4
8  3  8
13 8  7
16 5  7
18 3  6
19 3  5
20 5  6

Example2

 Live Demo

x2<-sample(LETTERS[1:5],20,replace=TRUE)
y2<-sample(LETTERS[1:3],20,replace=TRUE)
df2<-data.frame(x2,y2)
df2

Output

   x2 y2
1  A  B
2  D  B
3  C  A
4  D  C
5  D  B
6  A  C
7  A  A
8  B  C
9  E  C
10 D  A
11 D  B
12 D  B
13 E  C
14 B  C
15 B  A
16 B  A
17 C  B
18 E C
19 A C
20 C B

Subsetting df2 by using the opposite of %in% −

subset(df2,!(x2 %in% c("D","E")))

   x2 y2
1  A  B
3  C  A
6  A  C
7  A  A
8  B  C
14 B  C
15 B  A
16 B  A
17 C  B
19 A  C
20 C  B

Updated on: 06-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements