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

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

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

• Then, use rowSums function along with ncol function to find the percent of zeros in each row of the data.table object.

## Example

#### Create the data.table object

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

library(data.table)
v1<-sample(0:2,25,replace=TRUE)
v2<-sample(0:2,25,replace=TRUE)
v3<-sample(0:2,25,replace=TRUE)
v4<-sample(0:2,25,replace=TRUE)
v5<-sample(0:2,25,replace=TRUE)
DT<-data.table(v1,v2,v3,v4,v5)
DT

## Output

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

   v1 v2 v3 v4 v5
1:  2 1  1  1  1
2:  1 2  2  2  1
3:  1 2  1  0  1
4:  1 1  0  2  0
5:  0 1  0  0  2
6:  0 0  0  2  1
7:  0 0  1  0  0
8:  1 2  1  1  2
9:  1 2  2  1  0
10: 1 1  1  2  0
11: 1 2  0  0  0
12: 2 2  0  0  0
13: 2 2  2  2  2
14: 2 2  1  1  0
15: 2 1  0  2  2
16: 1 1  2  0  2
17: 0 0  2  1  1
18: 2 1  2  1  1
19: 2 1  2  2  1
20: 1 0  2  0  2
21: 0 0  2  2  2
22: 2 0  1  2  0
23: 0 2  2  1  0
24: 2 1  2  1  1
25: 2 2  2  0  2
v1 v2 v3 v4 v5

Find the percent of zeros in each row

Using rowSums function along with ncol function to find the percent of zeros in each row of the data.table object DT −

library(data.table)
v1<-sample(0:2,25,replace=TRUE)
v2<-sample(0:2,25,replace=TRUE)
v3<-sample(0:2,25,replace=TRUE)
v4<-sample(0:2,25,replace=TRUE)
v5<-sample(0:2,25,replace=TRUE)
DT<-data.table(v1,v2,v3,v4,v5)
DT\$Percent_0s<-(rowSums(DT==0)/ncol(DT))*100
DT

## Output

   v1 v2 v3 v4 v5 Percent_0s
1:  2  1 1  1  1  0
2:  1  2 2  2  1  0
3:  1  2 1  0  1 20
4:  1  1 0  2  0 40
5:  0  1 0  0  2 60
6:  0  0 0  2  1 60
7:  0  0 1  0  0 80
8:  1  2 1  1  2  0
9:  1  2 2  1  0 20
10: 1  1 1  2  0 20
11: 1  2 0  0  0 60
12: 2  2 0  0  0 60
13: 2  2 2  2  2  0
14: 2  2 1  1  0 20
15: 2  1 0  2  2 20
16: 1  1 2  0  2 20
17: 0  0 2  1  1 40
18: 2  1 2  1  1  0
19: 2  1 2  2  1  0
20: 1  0 2  0  2 40
21: 0  0 2  2  2 40
22: 2  0 1  2  0 40
23: 0  2 2  1  0 40
24: 2  1 2  1  1  0
25: 2  2 2  0  2 20
v1 v2 v3 v4 v5 Percent_0s