代码是这样的
x <- 1:5
x[NA]
为什么它会产生 5 个 NA?
最佳答案
这个问题的答案有两个方面:
索引矩阵时如何解释 NA?
在 one of the links由@alexis_laz 提供,我找到了一个结构很好的解释TRUE
, FALSE
和 NA
在索引矩阵时被解释:
Logical
indices tellR
which elements to include or exclude.You have three options:
TRUE
,FALSE
andNA
They serve to indicate whether or not the index represented in that position should be included. In other words:
TRUE == "Include the elment at this index" FALSE == "Do not include the element at this index" NA == "Return NA instead of this index" # loosely speaking
For example:
x <- 1:6 x[ c(TRUE, FALSE, TRUE, NA, TRUE, FALSE)] # [1] 1 3 NA 5
一个重要的细节是隔离
NA
的默认存储模式值是合乎逻辑的(尝试 typeof(NA)
)。可以选择NA
的存储方式通过使用 NA_integer_
, NA_real_
(双人),NA_complex_
或 NA_character_
.为什么 5
NA
而不仅仅是1? 当索引长度小于向量长度时
x
,索引将重新开始以同时索引 x
中的值尚未编入索引。换句话说,R
将自动“回收”索引:(...) However, standard recycling rules apply. So in the previous example, if we drop the last
FALSE
, the index vector is recycled, the first element of the index isTRUE
, and hence the 6th element ofx
is now includedx <- 1:6 x[c(TRUE, FALSE, TRUE, NA, TRUE)] # [1] 1 3 NA 5 6
回想上一节中有关存储模式的详细信息。如果您键入
x[NA_integer_]
,那么你会发现不同的结果。
关于r - 为什么 x[NA] 会产生与 x 长度相同的 NA 向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38240241/