首页 > 解决方案 > R:在 R 调试中,stop() 函数的具体用途是什么?

问题描述

我读了一些stop()在 R中使用的例子。

通常,stop()被放在函数的某个地方。

与使用以下代码有什么区别:

print('some error may be here') # as stop() also prints a message
return(NULL) # this can also stop the function immediately

那么我们如何才能更好地使用stop()in debug 呢?谢谢你。

标签: r

解决方案


stop()用于防止后续代码运行。它通常用于具有内置检查功能的更复杂的函数中,以避免在可能出现错误时运行复杂的计算。

例如,假设我有一个将数值向量作为输入的函数,但如果用户没有提供数值向量,我想停止函数并返回错误消息。

some_fun <- function(x) {

  if(!is.numeric(x)) {
     stop("x is not numeric") # use stop to prevent rest of function from running
  }

  # Complex computations...
}

> some_fun(c("a", "b", "c"))
Error in some_fun(c("a", "b", "c")) : x is not numeric

推荐阅读