【问题标题】:TryCatch exception handling in RR 中的 TryCatch 异常处理
【发布时间】:2020-09-23 04:26:11
【问题描述】:

我有一个按逻辑接受输入和返回的函数,我是 trycatch 的新手,无法获得我想要的相应结果,如果有人可以提供帮助,我将不胜感激

  1. 如果库 SHAPforxgboost 不存在,我想停止该功能并返回异常,说明请安装库

  2. 我必须检查函数的输入,如果不是数据框或矩阵,请停止函数并返回异常/错误,说明输入错误,请仅输入数据框或矩阵作为输入。

如果可能的话,有没有更好的方法来检查输入,根据我的逻辑,这似乎是一种笨拙的方法来检查数据框或矩阵是否存在

example<-function(a){
  
  library("SHAPforxgboost")    ### Throw an custom error that library is not present please install                            
                               ### the  library and stop the function and return the error as o/p
   
                              ### Similarly if the input is not dataframe or matrix, stop the function 
                              ### and return custom error wrong input
  if("data.frame"==class(a)){
      print("correct input")
  }else if("matrix"==class(a)){
    print("correct input")
  } else{print("wrong input")}  
  return(x)
}
e<-as.vector(3)
s<-as.data.frame(4)
p<-as.matrix(2)
example(e)
example(s)
example(p)


【问题讨论】:

    标签: r dplyr tidyverse tidyr


    【解决方案1】:

    你可以检查条件,如果条件不满足,可以stop执行。

    example<-function(a){
    
      if(!'SHAPforxgboost' %in% rownames(installed.packages()))
        stop('Please install SHAPforxgboost library')
      if(!(is.data.frame(a) | is.matrix(a)))
        stop('data should be either dataframe or matrix')
      #Do something
      #Do something
      #Return something
      return(x)
    }
    

    【讨论】:

    • @Ronakshah 我们可以使用 trycatch 实现同样的效果吗
    • 是的,也许。虽然我认为这不是tryCatch 的正确用法。 tryCatch 可用于处理代码中的警告或错误。 library('SHAPforxgboost') 如果未安装,则会产生错误,因此可以使用 tryCatch 覆盖该部分,但检查数据是数据帧还是矩阵不会产生警告或错误。
    • 您应该为此使用stopifnot
    猜你喜欢
    • 1970-01-01
    • 2021-05-11
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 2020-08-23
    • 2011-02-07
    • 2013-04-01
    相关资源
    最近更新 更多