gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:58:09 25 4
gpt4 key购买 nike

代码是这样的

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com