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

查看:13
本文介绍了用 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
  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:

对于 [-indexing only: 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天全站免登陆