How to find the number of zeros in each row of an R data frame?


To find the number of zeros in each row of an R data frame, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use rowSums function to find the number of zeros in each row of the data frame.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-rpois(25,2)
y<-rpois(25,2)
z<-rpois(25,2)
df<-data.frame(x,y,z)
df

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   x y z
1  3 1 1
2  3 4 3
3  2 5 3
4  1 0 3
5  2 2 2
6  1 1 2
7  3 1 5
8  1 3 2
9  1 2 4
10 1 4 4
11 2 2 1
12 3 3 2
13 1 4 1
14 2 3 1
15 3 4 4
16 2 0 1
17 0 4 1
18 4 1 2
19 2 5 2
20 0 1 1
21 1 2 2
22 4 2 3
23 2 4 2
24 5 0 0
25 1 2 3

Find the number of zeros in each row

Using rowSums function to find the number of zeros in each row of the data frame df −

x<-rpois(25,2)
y<-rpois(25,2)
z<-rpois(25,2)
df<-data.frame(x,y,z)
df$Total_0s<-rowSums(df==0)
df

Output

   x y z Total_0s
1  1 1 1 0
2  1 0 3 1
3  2 2 3 0
4  2 0 1 1
5  3 2 2 0
6  2 4 3 0
7  2 1 0 1
8  0 0 3 2
9  4 2 0 1
10 1 2 2 0
11 2 2 0 1
12 1 2 3 0
13 1 1 1 0
14 1 0 2 1
15 2 7 2 0
16 3 3 1 0
17 1 2 1 0
18 1 1 0 1
19 2 1 0 1
20 2 1 1 0
21 1 4 2 0
22 0 1 3 1
23 3 4 2 0
24 2 2 6 0
25 4 5 1 0

Updated on: 10-Nov-2021

642 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements