gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:42:45 25 4
gpt4 key购买 nike

我从以下内容中得到了有趣的结果,但不知道为什么。

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_logical_而没有指定类型,它只是回收 NAlength向量即 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com