Finding the index of an NA value in a vector

SavedByJESUS picture SavedByJESUS · May 24, 2014 · Viewed 51.5k times · Source

I have the following vector:

x <- c(3, 7, NA, 4, 8)

And I just want to know the index of the NA in the vector. If, for instance, I wanted to know the index of 7, the following code would work:

> which(x == 7)
[1] 2

I find it odd that running the same code when trying to find the index of the NA does not give me the desired result.

> which(x == NA)
integer(0)

I also tried the following but it does not work:

>  which(x == "NA")
integer(0)

Your help will be much appreciated.

Edit

The question has been answered below by @ccapizzano, but can anyone explain why the codes above do not work?

Answer

ccapizzano picture ccapizzano · May 24, 2014

You may want to try using the which and is.na functions in the the following manner:

which(is.na(x))
[1] 3