[英]Indexing integer vector with NA
I have problems understanding this.我在理解这一点时遇到了问题。 I have an integer vector of length 5:
我有一个长度为 5 的整数向量:
x <- 1:5
If I index it with a single NA
, the result is of length 5:如果我用单个
NA
对其进行索引,则结果长度为 5:
x[NA]
# [1] NA NA NA NA NA
My first idea was that R checks whether 1-5 is NA
but我的第一个想法是 R 检查 1-5 是否为
NA
但
x <- c(NA, 2, 4)
x[NA]
# NA NA NA.
So this cannot be the solution.所以这不可能是解决方案。 My second approach is that
x[NA]
is indexing but then I do not understand我的第二种方法是
x[NA]
正在编制索引,但我不明白
NA's
NA's
x[1]
gives you the first value but what should be the result of x[NA]
? x[1]
给你第一个值,但x[NA]
的结果应该是什么?Compare your code:比较你的代码:
> x <- 1:5; x[NA]
[1] NA NA NA NA NA
with与
> x <- 1:5; x[NA_integer_]
[1] NA
In the first case, NA
is of type logical ( class(NA)
shows), whereas in the second it's an integer.在第一种情况下,
NA
是逻辑类型( class(NA)
显示),而在第二种情况下它是一个整数。 From ?"["
you can see that in the case of i
being logical, it is recycled to the length of x
:从
?"["
你可以看到,在i
是逻辑的情况下,它被回收到x
的长度:
For [-indexing only: i, j, ... can be logical vectors, indicating elements/slices to select.
对于 [-indexing only: i, j, ... 可以是逻辑向量,指示要选择的元素/切片。 Such vectors are recycled if necessary to match the corresponding extent.
如有必要,这些向量会被回收以匹配相应的范围。 i, j, ... can also be negative integers, indicating elements/slices to leave out of the selection.
i, j, ... 也可以是负整数,表示元素/切片不在选择范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.