r - 为什么 x[NA] 会产生与 x 长度相同的 NA 向量?

标签 r

代码是这样的

x <- 1:5
x[NA]

为什么它会产生 5 个 NA?

最佳答案

这个问题的答案有两个方面:
索引矩阵时如何解释 NA?
one of the links由@alexis_laz 提供,我找到了一个结构很好的解释TRUE , FALSENA在索引矩阵时被解释:

Logical indices tell R which elements to include or exclude.

You have three options: TRUE, FALSE and NA

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 is TRUE, and hence the 6th element of x is now included

x <- 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/

相关文章:

r - 从列表列表到长格式的 tibble

r - 如何使用 ggcoefstats 在 R 中呈现多个 BTERGM 的结果?

r - 根据给定类型计算连续值

python - R 或 Python 中的频繁模式增长

r - .RDataTmp 临时文件的用途? [R]

r - 错误: installation of package ‘rgl’ had non-zero exit status

r - xts - 如何在一周中的每一天进行子集化

r - 在 R 中查找时间序列峰值的开始和结束

r - 如何使用dplyr将函数应用于所有非group_by列?

r - 如何创建一个因子但保留基础值,而不仅仅是整数代码?