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?
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 == ).
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.
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.
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).
You may want to try using the which
and is.na
functions in the the following manner:
which(is.na(x))
[1] 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With