在r中结合两个功能(使用TryCatch)

发布于 2025-01-28 18:13:00 字数 1124 浏览 1 评论 0原文

我想制作一个具有3个技能

  1. 的新功能,如果发生错误,请打印“错误”。不要停止整个过程,使其继续进行

  2. 如果发生警告,请继续进行

    ,请打印警告消息

  3. 如果没有错误和警告,请打印“无”。

对于1)我的函数如下:

efunc <- function(error){
  return(NA) 
}

tryc <- function(x){tryCatch(x, error = efunc)}


2),3),我参考此页面(我如何保存警告和错误作为功能的输出?)和 调整了一些代码,使以下功能


myTryCatch <- function(expr) {
  warn <- err <- NULL
  value <- withCallingHandlers(
    tryCatch(expr, error=function(e) {
      err <<- e                        # <<- is not typo
      print("error")
    }), warning=function(w) {
      warn <<- w                      # <<- is not typo
      invokeRestart("muffleWarning")
    })
  if(is.null(warn)){
    warn<-'Nothing'
  }
  if(is.null(err)){
    err<-'Nothing'
  }
  warning=warn
  paste(unlist(warning),collapse="")


}

回想,也许可以结合这两个功能。 或者,mytrycatch()已经具有Tryc()的技能。 但是我不确定。

I want to make a new function that has 3 skills

  1. if an error occurs, print "error". Do not stop the whole process, make it keep going

  2. if a warning occurs, print the warning message

  3. if there is no error nor warning, print "Nothing".

For 1) I made a function as follows:

efunc <- function(error){
  return(NA) 
}

tryc <- function(x){tryCatch(x, error = efunc)}


for 2), 3) , I refer to this page( How do I save warnings and errors as output from a function?) and
adapted some code, making the following functions


myTryCatch <- function(expr) {
  warn <- err <- NULL
  value <- withCallingHandlers(
    tryCatch(expr, error=function(e) {
      err <<- e                        # <<- is not typo
      print("error")
    }), warning=function(w) {
      warn <<- w                      # <<- is not typo
      invokeRestart("muffleWarning")
    })
  if(is.null(warn)){
    warn<-'Nothing'
  }
  if(is.null(err)){
    err<-'Nothing'
  }
  warning=warn
  paste(unlist(warning),collapse="")


}

However, thinking back, maybe it is possible to combine these two functions..
or, myTryCatch() already has a tryc()'s skill..
but I am not sure.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文