R 是否有像 python 中那样的断言语句?

发布于 2024-08-21 01:05:20 字数 37 浏览 4 评论 0原文

检查某事是否为真的语句,如果不为真则打印给定的错误消息并退出

a statement that checks if something is true and if not prints a given error message and exits

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

多情癖 2024-08-28 01:05:20

stopifnot()< /a>

您可能还对 Runittestthat 用于单元测试。

stopifnot()

You may also be interested in packages like Runit and testthat for unit testing.

情释 2024-08-28 01:05:20

@Nick:

如果您编写一个具有描述性名称的函数来测试将在程序中引发错误的条件,您可以控制错误消息。下面是一个示例:

Less_Than_8 = function(x) return(x < 8)

for (i in 1:10)
{
  print(i)
  stopifnot(Less_Than_8(i))
}

这将打印数字 1 到 8,然后打印一条消息,显示

Error: Less_Than_8(i) is not TRUE

如果括号中的“i”被替换为未通过测试的值,那就太好了,但一分钱一分货。

如果您需要比这更奇特的东西,请研究 Runit 并按照 Harlan 的建议进行测试。

@Nick:

You can control your error message if you write a function with a descriptive name to test the condition that will throw an error in your program. Here's an example:

Less_Than_8 = function(x) return(x < 8)

for (i in 1:10)
{
  print(i)
  stopifnot(Less_Than_8(i))
}

This will print the numbers 1 through 8, then print a message that says

Error: Less_Than_8(i) is not TRUE

It would be nice if the "i" in parentheses was replaced with the value that failed the test, but you get what you pay for.

If you need anything fancier than that, look into Runit and testthat as Harlan suggested.

苍风燃霜 2024-08-28 01:05:20

这可以通过 stop 命令来实现。该命令将停止函数的执行并打印错误消息。例如,我们可以测试变量 something 是否为 FALSE

if(something == FALSE){
   stop("error message to print")   
}

同样,warning 命令会打印警告(但继续执行代码) 。

if(something == FALSE){
   warning("error message to print")   
}

这些都是由基础 R 提供的,不需要任何包来运行或包含在编写您自己的函数中。我更喜欢这种方法来编写依赖较少的代码,并且这种语法广泛用于包开发中。然而,带有 assert_that 函数的“assertthat”包支持类似的功能,该函数最近作为 Hadley 的“tidyverse”的一部分发布。

This can be achieved with the stop command. This command will halt the execution of a function and print the error message. For example, we can test if the variable something is FALSE:

if(something == FALSE){
   stop("error message to print")   
}

Similarly, the warning command will print a warning (but continue executing the code).

if(something == FALSE){
   warning("error message to print")   
}

These are both provided by base R and require no packages to run or include in writing your own functions. I prefer this approach to write code with fewer dependancies and this syntax is widely used in package development. However, similar functionality is supported by the "assertthat" package with the assert_that function that has recently been released as part of Hadley's "tidyverse".

短暂陪伴 2024-08-28 01:05:20

testit-package

testit-package 提供了 assert- 函数作为简单的解决方案
(https://github.com/yihui/testit)

示例:

assert('one equals one', 1==1)
assert('seq and : produce equal sequences', seq(1L, 10L) == 1L:10L)
assert('seq and : produce identical sequences', identical(seq(1L, 10L), 1L:10L))

# multiple tests
T=FALSE; F=TRUE
assert('T is bad for TRUE, and so is F for FALSE', T!=TRUE, F!=FALSE)

# a mixture of tests
assert("Let's pray all of them will pass", 1==1, 1!=2, letters[4]=='d', rev(rev(letters))==letters)

来源:https://github.com/yihui/testit/blob/master/R/testit.R

The testit-package

The testit-package provides the assert-function as a simple solution
(https://github.com/yihui/testit)

Examples:

assert('one equals one', 1==1)
assert('seq and : produce equal sequences', seq(1L, 10L) == 1L:10L)
assert('seq and : produce identical sequences', identical(seq(1L, 10L), 1L:10L))

# multiple tests
T=FALSE; F=TRUE
assert('T is bad for TRUE, and so is F for FALSE', T!=TRUE, F!=FALSE)

# a mixture of tests
assert("Let's pray all of them will pass", 1==1, 1!=2, letters[4]=='d', rev(rev(letters))==letters)

Source: https://github.com/yihui/testit/blob/master/R/testit.R

秋凉 2024-08-28 01:05:20

您可以使用 checkmate 包来实现这一点。从他们的一个例子来看:

require(checkmate)

fact <- function(n, method = "stirling") {
  assertCount(n)
  assertChoice(method, c("stirling", "factorial"))

  if (method == "factorial")
    factorial(n)
  else
    sqrt(2 * pi * n) * (n / exp(1))^n
}

fact(2, method = 'blub')

You could use the checkmate-package for that. From one of their examples:

require(checkmate)

fact <- function(n, method = "stirling") {
  assertCount(n)
  assertChoice(method, c("stirling", "factorial"))

  if (method == "factorial")
    factorial(n)
  else
    sqrt(2 * pi * n) * (n / exp(1))^n
}

fact(2, method = 'blub')
我家小可爱 2024-08-28 01:05:20

之前对这个问题的回答已经过时了,所以我想我应该添加一个使用现代包的答案。 R 中的断言程序包此处有很好的描述此处记录。 assertr 包使用两个主要函数来验证数据集:verify 使用传递给它的数据帧的范围来计算布尔表达式,如果满足以下条件,将抛出错误并将错误记录在数据集的属性中:该表达式返回FALSE。如果发现错误,您可以选择继续处理数据集,并将错误视为警告,或者您可以指示 R 终止处理。这对于验证数据帧结构和内容很有用。例如,使用 cars 数据集,人们可能想要验证它是否包含 32 行数据。可以通过以下方式执行此操作:

library(assertr)
cars %>% verify(nrow(.)==32, error_fun = error_append) %>% 
  attributes() %>% 
  pluck("assertr_errors")

assertr_errors 属性将包含未通过验证检查的验证错误列表,因此上面将生成以下内容:

[[1]]
verification [nrow(.) == 32] failed! (1 failure)

    verb redux_fn     predicate column index value
1 verify       NA nrow(.) == 32     NA     1    NA

您还可以使用 添加其他验证检查>assert 函数如下面的链接所述。例如,继续上面的示例,我们可以验证变量速度中的观察值是否超过 23:

#Function that returns false if rule fails
is_greater_than_23<-function(x){
  x <=23
}

cars %>% assert(is_greater_than_23, speed, error_fun = error_append) %>% 
  attributes() %>% 
  pluck("assertr_errors")

其返回:

[[1]]
Column 'speed' violates assertion 'is_greater_than_23' 5 times
    verb redux_fn          predicate column index value
1 assert       NA is_greater_than_23  speed    46    24
2 assert       NA is_greater_than_23  speed    47    24
3 assert       NA is_greater_than_23  speed    48    24
4 assert       NA is_greater_than_23  speed    49    24
5 assert       NA is_greater_than_23  speed    50    25

值得注意的是,在上面的示例中,我将 error_append 分配给了 < verifyassert 函数调用的 code>error_fun 参数。这允许 R 在检查失败时继续处理数据,并将检测到的错误记录到 assertr_errors 属性中。一旦您收集了此属性中的错误,您就可以执行各种检查和其他验证步骤,再次在下面的链接中记录。如果您希望程序在遇到错误时停止处理,只需将 error_append 更改为 error_report,它“以“整洁”的方式打印有关错误的所有可用信息。 data.frame(包括所用谓词的名称、有问题的值等信息)并停止执行。”

The previous responses to this question are quite dated, so I figured I'd add an answer that uses a modern package. The assertr package in R is described well here and documented here. The assertr package makes uses of two primary functions to validate datasets: verify evaluates a boolean expression using the scope of a dataframe passed to it, and will throw, and log the error in the attributes of the dataset if the expression returns FALSE. You can choose to continue processing the dataset if an error is discovered and treat the error much like a warning or you can instruct R to terminate processing. This is useful for verifying dataframe structures and content. For example, using the cars dataset, one might want to verify that it contains 32 rows of data. One could do this with:

library(assertr)
cars %>% verify(nrow(.)==32, error_fun = error_append) %>% 
  attributes() %>% 
  pluck("assertr_errors")

The assertr_errors attribute will contain a list of validation errors that did not pass the verify check, so the above would produce the following:

[[1]]
verification [nrow(.) == 32] failed! (1 failure)

    verb redux_fn     predicate column index value
1 verify       NA nrow(.) == 32     NA     1    NA

You could also add other verification checks using the assert function as documented in the links below. For example, continuing with the example above, we can verify that no observation in the variable speed exceeds the value of 23:

#Function that returns false if rule fails
is_greater_than_23<-function(x){
  x <=23
}

cars %>% assert(is_greater_than_23, speed, error_fun = error_append) %>% 
  attributes() %>% 
  pluck("assertr_errors")

Which returns:

[[1]]
Column 'speed' violates assertion 'is_greater_than_23' 5 times
    verb redux_fn          predicate column index value
1 assert       NA is_greater_than_23  speed    46    24
2 assert       NA is_greater_than_23  speed    47    24
3 assert       NA is_greater_than_23  speed    48    24
4 assert       NA is_greater_than_23  speed    49    24
5 assert       NA is_greater_than_23  speed    50    25

It's important to note that in the examples above I assigned error_append to the error_fun argument of the verify and assert function calls. This allows R to continue processing the data when the check fails and logs the errors it detected to the assertr_errors attribute. Once you've gathered your errors in this attribute, you can do all sorts of checking and additional verification steps as documented, again, in the links below. If you want the program to stop processing when an error is encountered, you simply change error_append to error_report, which "prints all the information available about the errors in a "tidy" data.frame (including information such as the name of the predicate used, the offending value, etc...) and halts execution."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文