我从以下内容中得到了有趣的结果,但不确定原因。
match(3, 1:2)
返回NA
c(1, 3)[NA]
返回NA NA
c(1, 3)[match(3, 1:2)]
返回NA
这是怎么回事?为什么第二个和第三个结果的长度不同?直观上,将 match(3, 1:2)
替换为其结果 NA
应该会得到相同的结果,但事实并非如此。是什么触发了这个?
最佳答案
有回收作用。 match
情况下,如果没有匹配到,则默认nomatch = NA_integer
c(1, 3)[match(3, 1:2)]
#[1] NA
而OP在未指定类型的情况下使用了NA_逻辑_
,并且它只是将NA
回收到向量的长度
,即2。如果我们进行类型转换,将得到相同的输出
c(1, 3)[as.logical(match(3, 1:2))]
#[1] NA NA
同样的事情可以反过来复制
c(1, 3)[NA_integer_]
#[1] NA
原因在?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.
关于r - 使用 NA 时向量长度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59849884/