How to filter rows by excluding a particular value in columns of the R data frame?

R ProgrammingServer Side ProgrammingProgramming

To filter rows by excluding a particular value in columns of the data frame, we can use filter_all function of dplyr package along with all_vars argument that will select all the rows except the one that includes the passed value with negation. For example, if we have a data frame called df and we want to filter rows by excluding value 2 then we can use the command

df%>%filter_all(all_vars(.!=2))

Example

Consider the below data frame −

 Live Demo

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

Output

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

Loading dplyr package and filtering rows of df1 by excluding 4 in all the columns −

Example

library(dplyr)
df1%>%filter_all(all_vars(.!=4))

Output

   x1 x2
1  6  5
2  3  5
3  8  7
4  5  1
5  2  7
6  3  5
7  5  9
8  9  1
9  5  5
10 6  3
11 3  7

Example

 Live Demo

y1<-rpois(20,2)
y2<-rpois(20,2)
df2<-data.frame(y1,y2)
df2

Output

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

Filtering rows of df2 by excluding 2 in all the columns −

Example

df2%>%filter_all(all_vars(.!=2))

Output

   y1 y2
1  0  3
2  1  1
3  1  3
4  3  0
5  0  5
6  0  0
7  5  5
8  1  1
9  3  3
10 3  1
11 1  1
12 3  0
raja
Published on 17-Mar-2021 06:48:58
Advertisements