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
Create a Reactive Function Outside the Shiny App
How to Make a Barplot with R from a Table
Highlight a Line in Ggplot with Multiple Lines
Get Dates of a Certain Weekday from a Year in R
Subset Dataframe Based on Posixct Date and Time Greater Than Datetime Using Dplyr
R: Calculate Means for Subset of a Group
Update Subset of Values in a Dataframe Column
How to Figure Third Friday of a Month in R
R: Convert Date from Character to Datetime
Rolling Join Grouped by a Second Variable in Data.Table
How to Manage a Table/Matrix to Obtain Information Using Conditions
Ggplot Legend - Scale_Colour_Manual Not Working
Draw Bloxplots in R Given 25,50,75 Percentiles and Min and Max Values
Nas Are Not Allowed in Subscripted Assignments
Ggplot2 Scale_X_Log10() Destroys/Doesn't Apply for Function Plotted via Stat_Function()