为什么 NULL == 1 return logical(0) 而不是 FALSE?
Why does NULL == 1 return logical(0) than FALSE?
为什么 NULL == 1
returns logical(0)
而不是 FALSE
?
identical(1, NULL)
returnsFALSE
,正确
我知道 ==
和 identical
不能互换使用,但是 NULL == 1
返回 logical(0)
的背后是什么?
当两个操作数的模式不同时,"=="
(或任何其他逻辑运算符)背后存在隐式类型强制转换。来自 ?"=="
:
If the two arguments are atomic vectors of different types, one is coerced to the type of the other, the (decreasing) order of precedence being "character", "complex", "numeric", "integer", "logical" and "raw".
这会给你一些难以置信的结果!
"0" == 0 ## TRUE
1L == 1.0 ## TRUE
因此在 ?identical
中提到 "=="
并没有真正按照人们的预期去做。
identical
不强制转换。事实上,如果你只看?identical
中的例子,你会看到(我稍微改了一下):
identical(1, NULL) ## FALSE -- don't try this with ==
identical(1, 1L) ## FALSE, stored as different types (modes)
NULL
非常多才多艺(或模糊)。参见 。 "=="
中发生的事情是 NULL
被强制转换为 numeric(0)
,因为 mode(1)
是 "numeric"
,而您实际上是在测试
numeric(0) == 1 ## NULL == 1
numeric(0) == c(1, 2) ## NULL == c(1, 2)
现在的问题是,为什么结果是logical(0)
? R 的 recycling rule (R-intro) 不适用吗?为什么上面的代码没有转换成下面的?
rep_len(numeric(0), 1) == 1 ## NA
rep_len(numeric(0), 2) == c(1, 2) ## NA NA
嗯,在recycling rule (R-lang),据说:
As from R 1.4.0, any arithmetic operation involving a zero-length vector has a zero-length result.
太棒了;这里故意没有回收。所以我们只得到 logical(0)
.
为什么 NULL == 1
returns logical(0)
而不是 FALSE
?
identical(1, NULL)
returnsFALSE
,正确
我知道 ==
和 identical
不能互换使用,但是 NULL == 1
返回 logical(0)
的背后是什么?
当两个操作数的模式不同时,"=="
(或任何其他逻辑运算符)背后存在隐式类型强制转换。来自 ?"=="
:
If the two arguments are atomic vectors of different types, one is coerced to the type of the other, the (decreasing) order of precedence being "character", "complex", "numeric", "integer", "logical" and "raw".
这会给你一些难以置信的结果!
"0" == 0 ## TRUE
1L == 1.0 ## TRUE
因此在 ?identical
中提到 "=="
并没有真正按照人们的预期去做。
identical
不强制转换。事实上,如果你只看?identical
中的例子,你会看到(我稍微改了一下):
identical(1, NULL) ## FALSE -- don't try this with ==
identical(1, 1L) ## FALSE, stored as different types (modes)
NULL
非常多才多艺(或模糊)。参见 "=="
中发生的事情是 NULL
被强制转换为 numeric(0)
,因为 mode(1)
是 "numeric"
,而您实际上是在测试
numeric(0) == 1 ## NULL == 1
numeric(0) == c(1, 2) ## NULL == c(1, 2)
现在的问题是,为什么结果是logical(0)
? R 的 recycling rule (R-intro) 不适用吗?为什么上面的代码没有转换成下面的?
rep_len(numeric(0), 1) == 1 ## NA
rep_len(numeric(0), 2) == c(1, 2) ## NA NA
嗯,在recycling rule (R-lang),据说:
As from R 1.4.0, any arithmetic operation involving a zero-length vector has a zero-length result.
太棒了;这里故意没有回收。所以我们只得到 logical(0)
.