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

前端 未结 4 992
情话喂你
情话喂你 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:27

    2019 update

    You can you use 'quietly' from the purrr package, which returns a list of output, result, warning and error. You can then extract each element by name. For instance, if you had a list, which you want to map a function over, and find the elements which returned a warning you could do

    library(purrr)
    library(lubridate)
    
    datelist <- list(a = "12/12/2002", b = "12-12-2003", c = "24-03-2005")
    
    # get all the everything
    quiet_list <- map(datelist, quietly(mdy))
    
    # find the elements which produced warnings
    quiet_list %>% map("warnings") %>% keep(~ !is.null(.))
    
    # or 
    quiet_list %>% keep(~ length(.$warnings) != 0)
    

    For this example it's quite trivial, but for a long list of dataframes where the NAs might be hard to spot, this is quite useful.

提交回复
热议问题