Warm tip: This article is reproduced from serverfault.com, please click

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

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

发布于 2020-12-03 09:19:11

我正在尝试从内部包函数(stop_quietly())中调用stop(),该函数应该会中断该函数并返回至顶行。除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是我从这篇博文中获取的退出函数,修改了error = NULL,从而抑制了R作为浏览器执行错误处理程序。我不希望函数终止于浏览器,我只希望它退出而不会在R CMD Check中引发错误。

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
Questioner
Jonathan Fluharty-Jaidee
Viewed
0
user2554330 2020-12-04 18:30:05

由于你的函数具有全局副作用,因此我认为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()returning运行的FALSE,因此这将阻止该检查中发生的错误。如果这在你的程序包中更有意义,则也可以使用tryCatchinsidecreate_directories()捕获来自下面的错误。