# How to find the percent of NA’s in data.table object rows in R?

To find the percent of NAs 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 and ncol function along with apply function to find the percent of NAs 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)
x1<-sample(c(NA,1,2,5,7,3),25,replace=TRUE)
x2<-sample(c(NA,1,2,5,7,3),25,replace=TRUE)
x3<-sample(c(NA,1,2,5,7,3),25,replace=TRUE)
x4<-sample(c(NA,1,2,5,7,3),25,replace=TRUE)
DT<-data.table(x1,x2,x3,x4)
DT

## Output

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

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

Find the percent of NAs in each row

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

library(data.table)
x1<-sample(c(NA,1,2,5,7,3),25,replace=TRUE)
x2<-sample(c(NA,1,2,5,7,3),25,replace=TRUE)
x3<-sample(c(NA,1,2,5,7,3),25,replace=TRUE)
x4<-sample(c(NA,1,2,5,7,3),25,replace=TRUE)
DT<-data.table(x1,x2,x3,x4)
DT\$NA_Percent<-rowSums(apply(is.na(DT),2,as.numeric))/ncol(DT)
DT

## Output

    x1 x2  x3 x4 NA_Percent
1:  3  1   5  5  0.00
2:  2  5  NA  1  0.25
3:  NA 5   2  7  0.25
4:  2  2   3  3  0.00
5:  5  1   3  1  0.00
6:  1 NA  NA NA  0.75
7:  7  1   5  5  0.00
8:  3  3   5  1  0.00
9:  5  3   7  3  0.00
10: NA 7   3  1  0.25
11: 1  3   7  3  0.00
12: NA 3  NA  2  0.50
13: NA 7  NA  2  0.50
14: 3  7   2  NA 0.25
15: 2  7   1  7  0.00
16: 5  3   7  3  0.00
17: 1  3   5  5  0.00
18: 1  3   1  1  0.00
19: 2  7  NA  1  0.25
20: 1  7   1  7  0.00
21: 1  1   3  5  0.00
22: 7  7  NA  2  0.25
23: NA 3   1  2  0.25
24: 3  NA  7  7  0.25
25: NA 7  NA  1  0.50
x1 x2  x3 x4 NA_Percent