Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of an NA value in a vector [duplicate]

Tags:

r

na

vector

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?

like image 542
SavedByJESUS Avatar asked May 24 '14 00:05

SavedByJESUS


People also ask

How do I find index in R?

Use the which() Function to Find the Index of an Element in R. The which() function returns a vector with the index (or indexes) of the element which matches the logical vector (in this case == ).

What is the index value of a vector?

Vector Indexing, or vector index notation, specifies elements within a vector. Indexing is useful when a MATLAB program only needs one element of a series of values. Indexing is often used in combination with repetition structures to conduct the same process for every element in an array.

How do I find missing values in R?

In R, the easiest way to find columns that contain missing values is by combining the power of the functions is.na() and colSums(). First, you check and count the number of NA's per column. Then, you use a function such as names() or colnames() to return the names of the columns with at least one missing value.

How do you remove Na from a variable?

To remove all rows having NA, we can use na. omit function. For Example, if we have a data frame called df that contains some NA values then we can remove all rows that contains at least one NA by using the command na. omit(df).


1 Answers

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

which(is.na(x))
[1] 3
like image 59
ccapizzano Avatar answered Sep 23 '22 03:09

ccapizzano