Reputation: 365
Can someone explain why NA is evaluated as TRUE when it's inside a vector, but FALSE when it's an element in a list? See below.
Big thanks for any help.
> is.numeric(c(1, 2, NA)[3])
[1] TRUE
> is.numeric(list(1, 2, NA)[[3]])
[1] FALSE
> typeof(c(1, 2, NA)[3])
[1] "double"
typeof(list(1, 2, NA)[[3]])
[1] "logical"
Upvotes: 5
Views: 264
Reputation: 887078
It is related to type coercion in the vector
to numeric
as vector
can have only a single type whereas each list
element can be of different type. By default, the NA
is logical
. According to ?NA
NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw. There are also constants NA_integer_, NA_real_, NA_complex_ and NA_character_ of the other atomic vector types which support missing values: all of these are reserved words in the R language.
If we want numeric NA
in a list
, use NA_real_
typeof(list(1, 2, NA_real_)[[3]])
[1] "double"
Upvotes: 6