Reputation: 1386
I'm getting interesting results from the following and am not sure why.
match(3, 1:2)
returns NA
c(1, 3)[NA]
returns NA NA
c(1, 3)[match(3, 1:2)]
returns NA
What's going on here? Why are the second and third results different lengths? Intuitively, substituting match(3, 1:2)
with its result NA
should come up with the same result but it doesn't. What triggers that?
Upvotes: 2
Views: 39
Reputation: 887148
There is recycling effect. In the case of match
, if there is no matches, by default nomatch = NA_integer
c(1, 3)[match(3, 1:2)]
#[1] NA
while the OP used a NA_logical_
while not specifying the type and it just recycles the NA
to the length
of the vector i.e. 2. If we do the type conversion, will get the same output
c(1, 3)[as.logical(match(3, 1:2))]
#[1] NA NA
Same thing can be replicated in reverse
c(1, 3)[NA_integer_]
#[1] NA
The reason is mentioned in ?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.
Logical computations treat NA as a missing TRUE/FALSE value, and so may return TRUE or FALSE if the expression does not depend on the NA operand.
Upvotes: 2