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

To find the number 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 to find the number of zeros in each column.

## Example 1

#### Create the data.table object

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

library(data.table)
x1<-sample(0:2,25,replace=TRUE)
x2<-sample(0:2,25,replace=TRUE)
x3<-sample(0:2,25,replace=TRUE)
DT1<-data.table(x1,x2,x3)
DT1

## Output

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

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

Find the number of zeros

Using colSums function to find the number of zeros in each column of data.table object DT1 −

library(data.table)
x1<-sample(0:2,25,replace=TRUE)
x2<-sample(0:2,25,replace=TRUE)
x3<-sample(0:2,25,replace=TRUE)
DT1<-data.table(x1,x2,x3)
colSums(DT1==0)

## Output

x1 x2 x3
5  6 7

## Example 2

#### Create the data.table object

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

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

## Output

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

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

Find the number of zeros

Using colSums function to find the number of zeros in each column of data.table object DT2 −

library(data.table)
y1<-round(rnorm(25),0)
y2<-round(rnorm(25),0)
y3<-round(rnorm(25),0)
DT2<-data.table(y1,y2,y3)
colSums(DT2==0)

## Output

y1 y2 y3
8 7 10

Updated on: 15-Nov-2021

67 Views 