r - 使用 NA 时向量长度不同

标签 r

我从以下内容中得到了有趣的结果,但不确定原因。

match(3, 1:2)

返回NA

c(1, 3)[NA]

返回NA NA

c(1, 3)[match(3, 1:2)]

返回NA

这是怎么回事?为什么第二个和第三个结果的长度不同?直观上,将 match(3, 1:2) 替换为其结果 NA 应该会得到相同的结果,但事实并非如此。是什么触发了这个?

最佳答案

有回收作用。 match情况下,如果没有匹配到,则默认nomatch = NA_integer

c(1, 3)[match(3, 1:2)]
#[1] NA

而OP在未指定类型的情况下使用了NA_逻辑_,并且它只是将NA回收到向量的长度,即2。如果我们进行类型转换,将得到相同的输出

c(1, 3)[as.logical(match(3, 1:2))]
#[1] NA NA

同样的事情可以反过来复制

c(1, 3)[NA_integer_]
#[1] NA

原因在?NA中提到

NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw. There are also constants NA_integer_, NA_real_, NA_complex_ and NA_character_ of the other atomic vector types which support missing values: all of these are reserved words in the R language.

Logical computations treat NA as a missing TRUE/FALSE value, and so may return TRUE or FALSE if the expression does not depend on the NA operand.

关于r - 使用 NA 时向量长度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59849884/

相关文章:

按组在 R 中的数据框上运行自定义函数

r - data.table 在数字和文本变量上分别分组

php - 将 R 语言与 php 集成以从 R 中获取结果

r - 在 R 中,如何向列名添加一串文本?

r - 如何创建一个函数来获取汇总统计数据作为列?

r - 自定义 tm_compass() 背景

r - 在R中的两个月之间插入每月日期

R:计数 15 分钟的时间间隔

r - knitr 图、标签和标题在一个 block 中

r - R中的部分向量加法