Indexing Integer Vector with Na

Indexing integer vector with NA

Compare your code:

> x <- 1:5; x[NA] 
[1] NA NA NA NA NA

with

> x <- 1:5; x[NA_integer_] 
[1] NA

In the first case, NA is of type logical (class(NA) shows), whereas in the second it's an integer. From ?"[" you can see that in the case of i being logical, it is recycled to the length of x:

For [-indexing only: i, j, ... can be logical vectors, indicating
elements/slices to select. Such vectors are recycled if necessary to
match the corresponding extent. i, j, ... can also be negative
integers, indicating elements/slices to leave out of the selection.

Why I get NA when I do indexing a vector (or dataframe) that do not match my condition?

Your assumption is kind of correct that is you get NA values when there is NA in the data.

The comparison yields NA values

iris_test$Sepal.Length < 0
#[1] NA FALSE FALSE FALSE.....

When you subset a vector with NA it returns NA. See for example,

iris$Sepal.Length[c(1, NA)]
#[1] 5.1 NA

This is what the second case returns. For first case, all the values are FALSE so you get numeric(0)

iris$Sepal.Length[FALSE]
#numeric(0)

Finding the index of an NA value in a vector

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

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


Related Topics



Leave a reply



Submit