在函数内调用 stop() 会导致 R CMD Check 抛出错误

Calling stop( ) within function causes R CMD Check to throw error

我正在尝试从内部包函数 (stop_quietly()) 中调用 stop( ),这应该会中断函数并 return 到顶线。这有效,除了 R CMD Check 认为这是一个错误,因为我强制停止。

如何绕过 R CMD 检查将其解释为错误?该函数需要停止,因为它需要用户输入作为确认,然后才能在给定位置创建文件目录树。该代码当前生成一条消息并停止该函数。

tryCatch({
      path=normalizePath(path=where, winslash = "\", mustWork = TRUE)
      message(paste0("This will create research directories in the following directory: \n",path))
      confirm=readline(prompt="Please confirm [y/n]:")
      if(tolower(stringr::str_trim(confirm)) %in% c("y","yes","yes.","yes!","yes?")){
         .....
         dir.create(path, ... [directories])
         .....
       }
       message("There, I did some work, now you do some work.")
      }
        else{
        message("Okay, fine then. Don't do your research. See if I care.")
        stop_quietly()
      }
    },error=function(e){message("This path does not work, please enter an appropriate path \n or set the working directory with setwd() and null the where parameter.")})

stop_quietly 是一个退出函数 I took from this post,修改了 error=NULL,它抑制 R 作为浏览器执行错误处理程序。我不希望该功能终止到浏览器我只是希望它退出而不在 R CMD 检查中抛出错误。

stop_quietly <- function() {
  opt <- options(show.error.messages = FALSE, error=NULL)
  on.exit(options(opt))
  stop()
}

这是 R CMD 产生的错误的组成部分:

-- R CMD check results ------------------------------------------------ ResearchDirectoR 1.0.0 ----
Duration: 12.6s

> checking examples ... ERROR
  Running examples in 'ResearchDirectoR-Ex.R' failed
  The error most likely occurred in:
  
  > base::assign(".ptime", proc.time(), pos = "CheckExEnv")
  > ### Name: create_directories
  > ### Title: Creates research directories
  > ### Aliases: create_directories
  > 
  > ### ** Examples
  > 
  > create_directories()
  This will create research directories in your current working directory: 
  C:/Users/Karnner/AppData/Local/Temp/RtmpUfqXvY/ResearchDirectoR.Rcheck
  Please confirm [y/n]:
  Okay, fine then. Don't do your research. See if I care.
  Execution halted

由于您的函数具有全局副作用,我认为 check 不会喜欢它。如果您要求用户将 tryCatch 放在顶层,然后让它捕获错误,情况就会有所不同。但是想想这个场景:用户定义 f() 并调用它:

f <- function() {
  call_your_function()
  do_something_essential()
}
f()

如果您的函数以静默方式导致它跳过 f() 的第二行,可能会给用户带来很多麻烦。

您可以做的是告诉用户将对您的函数的调用包装在 tryCatch() 中,并让它捕获错误:

f <- function() {
  tryCatch(call_your_function(), error = function(e) ...)
  do_something_essential()
}
f()

这样用户就会知道你的函数失败了,并可以决定是否继续。

从评论中的讨论和您对问题的编辑来看,您的功能似乎仅打算用于交互使用,因此上述情况不是问题。在这种情况下,您可以通过跳过示例来避免 R CMD check 问题,除非它是 运行 交互。这相当简单:在 create_directories() 等函数的帮助页面中,将您的示例设置为

if (interactive()) {
  create_directories()
  # other stuff if you want
}

检查是 运行,interactive() 返回 FALSE,因此这将阻止错误在检查中发生。您也可以在 create_directories() 中使用 tryCatch 来捕捉从下面出现的错误,如果这在您的包中更有意义的话。