为什么空逻辑向量通过 stopifnot() 检查?

Kar*_*ius 6 error-handling boolean r is-empty

今天我发现我的一些stopifnot()测试失败了,因为传递的参数评估为空的逻辑向量。

下面是一个例子:

stopifnot(iris$nosuchcolumn == 2)  # passes without error
Run Code Online (Sandbox Code Playgroud)

这是非常不直观的,似乎与其他一些行为相矛盾。考虑:

isTRUE(logical())
> FALSE

stopifnot(logical())
# passes
Run Code Online (Sandbox Code Playgroud)

因此stopifnot(),即使此参数不是TRUE
但此外,上述行为对于不同类型的空向量是不同的。

isTRUE(numeric())
> FALSE

stopifnot(numeric())
# Error: numeric() are not all TRUE
Run Code Online (Sandbox Code Playgroud)

以上是否有一些逻辑,还是应该将其视为错误?

Fon*_* MA 1

stopifnot其他答案涵盖了其行为方式的实际原因;但我同意卡罗利斯的观点,即亨里克链接的线程添加了为什么会出现这种情况的真正解释:

作为 stopifnot() 的作者,我确实同意 [OP] 的“直觉”[...],即 stopifnot(dim(x) == c(3,4))[...][应该] 在 x 是简单向量而不是矩阵/数据的情况下停止。框架/...具有尺寸c(3,4)...但是[...]由于逻辑的基本引理,直觉是错误的:[...]

“所有关于空集元素的陈述都是正确的”

马丁·梅奇勒,苏黎世联邦理工学院

另外,[...],any() 是“|” sum() 相当于“+”,all() 相当于“&”,prod() 相当于“*”。所有运算符都有一个单位元素,分别为 FALSE、0、TRUE 和 1,通用约定是对于空向量,我们返回单位元素,原因如上所述。

彼得·D.