How to find the percent of NA’s in R data frame rows?


To find the percent of NAs 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 and ncol function along with apply function to find the percent of NAs in each row of the data frame

Example

Create the data frame

Let’s create a data frame as shown below −

v1<-sample(c(NA,rpois(3,2)),25,replace=TRUE)
v2<-sample(c(NA,rpois(3,2)),25,replace=TRUE)
v3<-sample(c(NA,rpois(3,2)),25,replace=TRUE)
v4<-sample(c(NA,rpois(3,2)),25,replace=TRUE)
df<-data.frame(v1,v2,v3,v4)
df

Output

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

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

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 frame df −

v1<-sample(c(NA,rpois(3,2)),25,replace=TRUE)
v2<-sample(c(NA,rpois(3,2)),25,replace=TRUE)
v3<-sample(c(NA,rpois(3,2)),25,replace=TRUE)
v4<-sample(c(NA,rpois(3,2)),25,replace=TRUE)
df<-data.frame(v1,v2,v3,v4)
df$NA_Percent<-rowSums(apply(is.na(df),2,as.numeric))/ncol(df)
df

Output

   v1 v2 v3 v4 NA_Percent
1   1  2  2  4 0.00
2   2  2  2  3 0.00
3   2  2 NA  3 0.25
4   2  1  4 NA 0.25
5   2  2 NA  1 0.25
6  NA NA  4 NA 0.75
7   2  2  4 NA 0.25
8   2  1  4  3 0.00
9   2  2  0  4 0.00
10  2  2  0 NA 0.25
11 NA  2  2 NA 0.50
12  2  2  0  4 0.00
13  1  2  4  1 0.00
14  1 NA  4  3 0.25
15  2 NA  4 NA 0.50
16  2 NA  4  3 0.25
17  2 NA NA  3 0.50
18  1  1 NA  4 0.25
19 NA  1 NA NA 0.75
20 NA  2  0  4 0.25
21  1  2  4  1 0.00
22  2  2  2  1 0.00
23  2  1  4  4 0.00
24  1  2  4 NA 0.25
25 NA NA NA  3 0.75

Updated on: 12-Nov-2021

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements