用NA索引整数向量 [英] Indexing integer vector with NA

查看:44
本文介绍了用NA索引整数向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解这一点.我有一个长度为5的整数向量:

I have problems understanding this. I have an integer vector of length 5:

x <- 1:5

如果我使用单个 NA 对其进行索引,则结果的长度为5:

If I index it with a single NA, the result is of length 5:

x[NA] 
# [1] NA NA NA NA NA

我的第一个想法是R检查1-5是否为 NA

My first idea was that R checks whether 1-5 is NA but

x <- c(NA, 2, 4)
x[NA] 
# NA NA NA.

所以这不是解决方案.我的第二种方法是 x [NA] 正在建立索引,但是我不理解

So this cannot be the solution. My second approach is that x[NA] is indexing but then I do not understand

  1. 这为什么给我五个 NA's
  2. NA作为索引的含义. x [1] 给您第一个值,但是 x [NA] 的结果应该是什么?
  1. Why this gives me five NA's
  2. What NA as an index means. x[1] gives you the first value but what should be the result of x[NA]?

推荐答案

比较您的代码:

> x <- 1:5; x[NA] 
[1] NA NA NA NA NA

> x <- 1:5; x[NA_integer_] 
[1] NA

在第一种情况下, NA 是逻辑类型( class(NA)显示),而在第二种情况下,它是整数.从?"[" 您可以看到,在 i 是逻辑的情况下,它被回收到 x 的长度:

In the first case, NA is of type logical (class(NA) shows), whereas in the second it's an integer. From ?"[" you can see that in the case of i being logical, it is recycled to the length of x:

仅对于[-索引:i,j,...可以是逻辑向量,指示要选择的元素/切片.如有必要,可将此类载体回收匹配相应的范围.i,j,...也可以是负数整数,指示要排除在选择之外的元素/切片.

For [-indexing only: i, j, ... can be logical vectors, indicating elements/slices to select. 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.

这篇关于用NA索引整数向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆