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

问题描述 投票:3回答:1

[今天,我发现某些stopifnot()测试失败,因为传递的参数求值为空逻辑向量。

这里是一个例子:

stopifnot(iris$nosuchcolumn == 2)  # passes without error

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

isTRUE(logical())
> FALSE

stopifnot(logical())
# passes

因此stopifnot()通过,即使此参数不是TRUE。但此外,上述行为在不同类型的空向量上也有所不同。

isTRUE(numeric())
> FALSE

stopifnot(numeric())
# Error: numeric() are not all TRUE

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

r error-handling boolean is-empty
1个回答
1
投票

akrun和r2evans的评论就在现场。

但是,要详细说明为什么会发生这种情况以及为什么您对isTRUE()行为感到困惑,请注意stopifnot()检查三件事;检查是(其中r是您传递的表达式的结果):

if (!(is.logical(r) && !anyNA(r) && all(r)))

所以,让我们看一下:

is.logical(logical())
# [1] TRUE
!anyNA(logical())
# [1] TRUE
all(logical())
# [1] TRUE

is.logical(numeric())
# [1] FALSE
!anyNA(numeric())
# [1] TRUE
all(numeric())
# [1] TRUE

因此,logical()通过而numeric()失败的唯一原因是因为numeric()不是akrun建议的“逻辑”。因此,应避免使用可能导致r2evans建议的长度为0的逻辑向量的检查。

© www.soinside.com 2019 - 2024. All rights reserved.