How to remove rows that contain at least one 0 in R?


To remove rows that contain at least one 0, we can use single square brackets for subsetting rows with apply that will select rows that do not contain even one zero. For example, if we have a data frame called df then we can remove rows that contain at least one 0 can be done by using the command df[apply(df,1, function(x) all(x!=0)),].

Example

Consider the below data frame −

 Live Demo

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

Output

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

Removing rows of df1 that do not contain at least one 0 −

Example

df1[apply(df1,1, function(x) all(x!=0)),]

Output

   x1 x2 x3
2  1  8  2
4  1  4  3
5  1  4  5
6  1  5  3
7  2 11  8
8  1  3  8
9  1  4  4
10 1  7  4
12 3  4  1
16 1  6  8
17 1  6  3
18 1  5  4
19 2  3  1

Example

 Live Demo

y1<-sample(0:2,20,replace=TRUE)
y2<-sample(1:5,20,replace=TRUE)
y3<-sample(1:10,20,replace=TRUE)
df2<-data.frame(y1,y2,y3)
df2

Output

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

Removing rows of df2 that do not contain at least one 0 −

Example

df2[apply(df2,1, function(x) all(x!=0)),]

Output

   y1 y2 y3
2  2  3  6
3  1  5  8
4  2  3  1
5  1  5  5
7  1  2 10
8  1  5  8
9  1  5  5
11 1  4  4
15 1  4  4
17 2  5  3
19 2  4  1

Updated on: 16-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements