How to check whether a vector contains an NA value or not in R?


An NA value in R represents “Not Available” that means missing value. If a vector has even one NA value then the calculations for that vector becomes a little difficult because we will either have to remove that NA, replace it or neglect it during the calculations. To do any of these things, we will have to make some changes in our codes therefore, it is better to check whether a vector contain an NA or not before doing anything. This can be done with the help of any function in conjunction with is.na.

Example

> x1<-c(1,2,3,2)
> x1
[1] 1 2 3 2
> any(is.na(x1))
[1] FALSE
> x2<-c(1,2,3,2,NA)
> x2
[1] 1 2 3 2 NA
> any(is.na(x2))
[1] TRUE
> x3<-c(4,5,6,"",2,8,7)
> x3
[1] "4" "5" "6" "" "2" "8" "7"
> any(is.na(x3))
[1] FALSE
> x4<-c(4,5,6,"NA",2,8,7)
> x4
[1] "4" "5" "6" "NA" "2" "8" "7"
> any(is.na(x4))
[1] FALSE
> x5<-c(4,5,6,4,2,8,7,NA,4,5,NA,NA)
> x5
[1] 4 5 6 4 2 8 7 NA 4 5 NA NA
> any(is.na(x5))
[1] TRUE
> x6<-rep(c(15,NA,10),times=10)
> x6
 [1] 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15
[26] NA 10 15 NA 10
> any(is.na(x6))
[1] TRUE
> x7<-rep(c(15,"NA",10),times=10)
> x7
 [1] "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10"
[16] "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10"
> any(is.na(x7))
[1] FALSE
> x8<-1:1000000
> any(is.na(x8))
[1] FALSE
> x9<-rep(c(1,2,3,4,5,6,7,8,9,10),times=500000)
> any(is.na(x9))
[1] FALSE
> x10<-rep(c(1,2,3,4,5,6,7,8,9,10),times=5000000)
> any(is.na(x10))
[1] FALSE

The vectors having small size will take less time to get the answer on the other hand the vectors having a very large size will take slightly more time to let us know whether we have an NA in our vector or not.

Updated on: 11-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements