简体   繁体   English

用 NA 索引整数向量

[英]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]正在编制索引,但我不明白

  1. Why this gives me five NA's为什么这给了我五个NA's
  2. What NA as an index means. NA 作为索引意味着什么。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM