gpt4 book ai didi

r - stopifnot()对于…中的一个表达式失败,并且不起作用,正如我期望的那样。我的期望正确吗?

转载 作者:行者123 更新时间:2023-12-03 07:49:48 24 4
gpt4 key购买 nike

R文档中stopifnot的描述

Description

If any of the expressions in ... are not all TRUE, stop is called, producing an error message indicating the first of the elements of ... which were not true.

Usage

stopifnot(...)

Arguments

... any number of (logical) R expressions, which should evaluate to TRUE.



有时...中的表达式的计算结果不为TRUE。考虑以下情况的错误消息
a <- 1:10
stopifnot(
class(a) %in% c("numeric", "integer"),
sum(a) >= 100
)

> Error: sum(a) >= 100 is not TRUE

很好但是,以下情况的错误消息不是我所期望的
a <- letters
stopifnot(
class(a) %in% c("numeric", "integer"),
sum(a) >= 100
)
> Error in sum(a) : invalid 'type' (character) of argument

我希望它能说

Error: class(a) %in% c("numeric", "integer") is not TRUE



但是,它没有。

我的期望正确吗?那是stopifnot()应该如何工作的? ,如何使stopifnot()像这样工作?

最佳答案

stopifnot评估您提供的每个表达式,然后检查它们是否均为TRUE。如果不是这种情况,它将暂停并打印一条错误消息,指出哪些表达式失败。

在您的示例中,正在发生的事情是表达式本身正在触发错误。导致错误消息的是表达式sum(a) >= 100的求值,而不是stopifnot本身。

关于r - stopifnot()对于…中的一个表达式失败,并且不起作用,正如我期望的那样。我的期望正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37344004/

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