How can I check whether a function call results in a warning?

前端 未结 4 1001
情话喂你
情话喂你 2020-11-29 23:00

In R, how can I determine whether a function call results in a warning?

That is, after calling the function I would like to know whether that instance of the call yi

4条回答
  •  被撕碎了的回忆
    2020-11-29 23:39

    If you want to use the try constructs, you can set the options for warn. See also ?options. Better is to use tryCatch() :

    x <- function(i){
      if (i < 10) warning("A warning")
      i
    }
    
    tt <- tryCatch(x(5),error=function(e) e, warning=function(w) w)
    
    tt2 <- tryCatch(x(15),error=function(e) e, warning=function(w) w)
    
    tt
    ## 
    
    tt2
    ## [1] 15
    
    if(is(tt,"warning")) print("KOOKOO")
    ## [1] "KOOKOO"
    
    if(is(tt2,"warning")) print("KOOKOO")
    

    To get both the result and the warning :

    tryCatch(x(5),warning=function(w) return(list(x(5),w)))
    
    ## [[1]]
    ## [1] 5
    ## 
    ## [[2]]
    ## 
    

    Using try

    op <- options(warn=2)
    
    tt <- try(x())
    ifelse(is(tt,"try-error"),"There was a warning or an error","OK")
    options(op)
    

提交回复
热议问题