# How to find the percentage of zeros in each column of a data.table object in R?

To find the percentage of zeros in each column of a data.table object in R, we can follow the below steps −

• First of all, create a data.table object.

• Then, use colSums function along with nrow function to find the percentage of zeros in each column.

## Example 1

#### Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
y1<-round(rnorm(25,1),0)
y2<-round(rnorm(25,1),0)
y3<-round(rnorm(25,1),0)
y4<-round(rnorm(25,1),0)
DT1<-data.table(y1,y2,y3,y4)
DT1

## Output

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

   y1 y2 y3 y4
1:  1  2  1  2
2:  2 -1  1  1
3:  2  0  1  2
4:  2  2  0  3
5:  3  1  0  2
6:  1  1  2  1
7:  1  4  2  2
8:  1  2  1  0
9:  1 -1  1  0
10: 1  1  2 -1
11: 1  1  0  0
12: 2  1  0  2
13: 0  0  1  1
14: 0  0  1  2
15: 0  2  0  1
16: 0 -1  1  1
17: 1  1  1  0
18: 2  2  1  0
19: 0  1  2  0
20: 1  0  0  1
21: 0  0  0  3
22: 1  3  3  2
23: 2  1  1  1
24: 1  2  1  1
25: 1  1  1  0
y1 y2 y3 y4

Find the percentage of zeros

Using colSums function along with nrow function to find the percentage of zeros in each column of data.table object DT1 −

library(data.table)
y1<-round(rnorm(25,1),0)
y2<-round(rnorm(25,1),0)
y3<-round(rnorm(25,1),0)
y4<-round(rnorm(25,1),0)
DT1<-data.table(y1,y2,y3,y4)
(colSums(DT1==0)/nrow(DT1))*100

## Output

y1 y2 y3 y4
24 20 28 28

## Example 2

#### Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
c1<-sample(0:5,25,replace=TRUE)
c2<-sample(0:5,25,replace=TRUE)
c3<-sample(0:5,25,replace=TRUE)
c4<-sample(0:5,25,replace=TRUE)
DT2<-data.table(c1,c2,c3,c4)
DT2

## Output

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

   c1 c2 c3 c4
1:  1  5 0  5
2:  3  2 2  5
3:  3  3 2  4
4:  3  5 2  1
5:  2  4 1  4
6:  0  2 1  3
7:  3  1 3  2
8:  1  3 3  4
9:  2  3 0  2
10: 1  3 5  4
11: 1  2 0  4
12: 3  3 5  1
13: 1  5 5  5
14: 1  1 4  4
15: 2  4 1  4
16: 3  5 4  3
17: 3  1 5  4
18: 5  4 5  2
19: 5  0 0  1
20: 4  5 2  2
21: 3  0 5  0
22: 0  5 5  3
23: 2  5 1  0
24: 4  5 5  1
25: 3  4 5  2
c1 c2 c3 c4

Find the percentage of zeros

Using colSums function along with nrow function to find the percentage of zeros in each column of data.table object DT2 −

library(data.table)
c1<-sample(0:5,25,replace=TRUE)
c2<-sample(0:5,25,replace=TRUE)
c3<-sample(0:5,25,replace=TRUE)
c4<-sample(0:5,25,replace=TRUE)
DT2<-data.table(c1,c2,c3,c4)
(colSums(DT2==0)/nrow(DT2))*100

## Output

c1 c2 c3 c4
8  8 16 8

Updated on: 11-Nov-2021

153 Views