How can I check whether a function call results in a warning?Use tryCatch skip to next value of loop upon error?How do I save warnings and errors as output from a function?R Shiny: Output warning messages to UIMultiple expectations with test_thatget indication of warnings in R sciriptWhy tryCatch returns no warnings when it was asked for producing them?How to see if R returns a warning but won't output it to the screen?Concatenate a vector of strings/characterPlot two graphs in same plot in RGrouping functions (tapply, by, aggregate) and the *apply familyDrop data frame columns by nameHow do I save warnings and errors as output from a function?Measuring function execution time in RHow can we make xkcd style graphs?Creating vector of results of repeated function calls in RInterpreting “condition has length > 1” warning from `if` functionHow can I view the source code for a function?

Is there a word for returning to unpreparedness?

Graphs for which a calculus student can reasonably compute the arclength

What unique challenges/limitations will I face if I start a career as a pilot at 45 years old?

Why does this Jet Provost strikemaster have a textured leading edge?

Match 4 columns and replace 1 in 2 files

Go to last file in vim

Weird resistor with dots around it

Are there liquid fueled rocket boosters having coaxial fuel/oxidizer tanks?

What would cause a nuclear power plant to break down after 2000 years, but not sooner?

The oceans and the moon

Scam? Phone call from "Department of Social Security" asking me to call back

How can I find an old paper when the usual methods fail?

A+ rating still unsecure by Google Chrome's opinion

Who is the controller of a Pacifism enchanting my creature?

Output the list of musical notes

What is the prop for Thor's hammer (Mjölnir) made of?

How much can I judge a company based on a phone screening?

How to gracefully leave a company you helped start?

Number in overlapping range

Why do my bicycle brakes get worse and feel more 'squishy" over time?

What can I do to increase the amount of LEDs I can power with a pro micro?

How to measure if Scrum Master is making a difference and when to give up

Why did IBM make the PC BIOS source code public?

Why does Japan use the same type of AC power outlet as the US?



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


Use tryCatch skip to next value of loop upon error?How do I save warnings and errors as output from a function?R Shiny: Output warning messages to UIMultiple expectations with test_thatget indication of warnings in R sciriptWhy tryCatch returns no warnings when it was asked for producing them?How to see if R returns a warning but won't output it to the screen?Concatenate a vector of strings/characterPlot two graphs in same plot in RGrouping functions (tapply, by, aggregate) and the *apply familyDrop data frame columns by nameHow do I save warnings and errors as output from a function?Measuring function execution time in RHow can we make xkcd style graphs?Creating vector of results of repeated function calls in RInterpreting “condition has length > 1” warning from `if` functionHow can I view the source code for a function?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








52















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 yielded a warning.










share|improve this question
























  • Check out if ?try does what you want.

    – Roman Luštrik
    Oct 11 '10 at 7:37











  • Closely related to stackoverflow.com/q/4948361 that provides some excellent answers with error catching as well.

    – JWilliman
    Nov 8 '18 at 23:27

















52















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 yielded a warning.










share|improve this question
























  • Check out if ?try does what you want.

    – Roman Luštrik
    Oct 11 '10 at 7:37











  • Closely related to stackoverflow.com/q/4948361 that provides some excellent answers with error catching as well.

    – JWilliman
    Nov 8 '18 at 23:27













52












52








52


14






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 yielded a warning.










share|improve this question














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 yielded a warning.







r






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Oct 11 '10 at 2:20









Alex HolcombeAlex Holcombe

1,2232 gold badges15 silver badges31 bronze badges




1,2232 gold badges15 silver badges31 bronze badges















  • Check out if ?try does what you want.

    – Roman Luštrik
    Oct 11 '10 at 7:37











  • Closely related to stackoverflow.com/q/4948361 that provides some excellent answers with error catching as well.

    – JWilliman
    Nov 8 '18 at 23:27

















  • Check out if ?try does what you want.

    – Roman Luštrik
    Oct 11 '10 at 7:37











  • Closely related to stackoverflow.com/q/4948361 that provides some excellent answers with error catching as well.

    – JWilliman
    Nov 8 '18 at 23:27
















Check out if ?try does what you want.

– Roman Luštrik
Oct 11 '10 at 7:37





Check out if ?try does what you want.

– Roman Luštrik
Oct 11 '10 at 7:37













Closely related to stackoverflow.com/q/4948361 that provides some excellent answers with error catching as well.

– JWilliman
Nov 8 '18 at 23:27





Closely related to stackoverflow.com/q/4948361 that provides some excellent answers with error catching as well.

– JWilliman
Nov 8 '18 at 23:27












4 Answers
4






active

oldest

votes


















63














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
## <simpleWarning in x(5): A warning>

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]]
## <simpleWarning in x(5): A warning>


Using try



op <- options(warn=2)

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





share|improve this answer






















  • 5





    thanks for your edit showing how to get both the result and the warning; however, the function is called twice when there's a warning. Can it be done with only one call (in case the function is slow, for example)?

    – Aaron
    Feb 10 '11 at 2:17











  • @Aaron : then I'd go for the handlers as shown below by you. That's the cleanest way, and those are made to do that. It just requires a bit more puzzling.

    – Joris Meys
    Feb 10 '11 at 8:56












  • Thanks. It is definitely puzzling. Though it does what I need, there's a lot in that code I don't yet understand.

    – Aaron
    Feb 10 '11 at 15:18


















22














On the R-help mailing list (see http://tolstoy.newcastle.edu.au/R/help/04/06/0217.html), Luke Tierney wrote:



"If you want to write a function that computes a value and collects all
warning you could do it like this:



withWarnings <- function(expr) 
myWarnings <- NULL
wHandler <- function(w)
myWarnings <<- c(myWarnings, list(w))
invokeRestart("muffleWarning")

val <- withCallingHandlers(expr, warning = wHandler)
list(value = val, warnings = myWarnings)






share|improve this answer




















  • 1





    is <<- correct?

    – isomorphismes
    Nov 11 '11 at 10:44






  • 4





    Yup, that way it updates the myWarnings outside the function; otherwise it makes a new myWarnings inside the function and the outside one doesn't get updated.

    – Aaron
    Nov 11 '11 at 16:33


















6














here is an example:



testit <- function() warning("testit") # function that generates warning.

assign("last.warning", NULL, envir = baseenv()) # clear the previous warning

testit() # run it

if(length(warnings())>0) # or !is.null(warnings())
print("something happened")



maybe this is somehow indirect, but i don't know the more straightforward way.






share|improve this answer

























  • Although this is inelegant, it's good because I can't find any other way to catch a warning and nevertheless return the normal result from the function. That is, if testit() returns a value, catching a warning with tryExcept means you lose the value. Unless I'm missing something?

    – Alex Holcombe
    Oct 22 '10 at 4:43






  • 1





    @Alex : you could do pretty easily using a tryCatch formula. You can do something with the warning in the argument, eg: warning=function(w) ...do something ... return(normal result)

    – Joris Meys
    Feb 4 '11 at 10:29











  • @Joris: I couldn't get tryCatch to return the normal result. Am I missing something? I did find a way using withCallingHandlers, from the R mailing list (included as a separate answer).

    – Aaron
    Feb 9 '11 at 16:21











  • @Aaron : see edit in my answer

    – Joris Meys
    Feb 9 '11 at 22:33











  • @AlexHolcombe You could also set options(warn=1) in which case the warnings are printed to stdout rather than stderr.

    – isomorphismes
    Nov 11 '11 at 9:30


















1














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.






share|improve this answer





























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3903157%2fhow-can-i-check-whether-a-function-call-results-in-a-warning%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    63














    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
    ## <simpleWarning in x(5): A warning>

    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]]
    ## <simpleWarning in x(5): A warning>


    Using try



    op <- options(warn=2)

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





    share|improve this answer






















    • 5





      thanks for your edit showing how to get both the result and the warning; however, the function is called twice when there's a warning. Can it be done with only one call (in case the function is slow, for example)?

      – Aaron
      Feb 10 '11 at 2:17











    • @Aaron : then I'd go for the handlers as shown below by you. That's the cleanest way, and those are made to do that. It just requires a bit more puzzling.

      – Joris Meys
      Feb 10 '11 at 8:56












    • Thanks. It is definitely puzzling. Though it does what I need, there's a lot in that code I don't yet understand.

      – Aaron
      Feb 10 '11 at 15:18















    63














    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
    ## <simpleWarning in x(5): A warning>

    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]]
    ## <simpleWarning in x(5): A warning>


    Using try



    op <- options(warn=2)

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





    share|improve this answer






















    • 5





      thanks for your edit showing how to get both the result and the warning; however, the function is called twice when there's a warning. Can it be done with only one call (in case the function is slow, for example)?

      – Aaron
      Feb 10 '11 at 2:17











    • @Aaron : then I'd go for the handlers as shown below by you. That's the cleanest way, and those are made to do that. It just requires a bit more puzzling.

      – Joris Meys
      Feb 10 '11 at 8:56












    • Thanks. It is definitely puzzling. Though it does what I need, there's a lot in that code I don't yet understand.

      – Aaron
      Feb 10 '11 at 15:18













    63












    63








    63







    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
    ## <simpleWarning in x(5): A warning>

    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]]
    ## <simpleWarning in x(5): A warning>


    Using try



    op <- options(warn=2)

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





    share|improve this answer















    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
    ## <simpleWarning in x(5): A warning>

    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]]
    ## <simpleWarning in x(5): A warning>


    Using try



    op <- options(warn=2)

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






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jul 27 '15 at 16:13









    Tyler Rinker

    67.5k46 gold badges248 silver badges432 bronze badges




    67.5k46 gold badges248 silver badges432 bronze badges










    answered Oct 11 '10 at 8:46









    Joris MeysJoris Meys

    84.5k25 gold badges184 silver badges247 bronze badges




    84.5k25 gold badges184 silver badges247 bronze badges










    • 5





      thanks for your edit showing how to get both the result and the warning; however, the function is called twice when there's a warning. Can it be done with only one call (in case the function is slow, for example)?

      – Aaron
      Feb 10 '11 at 2:17











    • @Aaron : then I'd go for the handlers as shown below by you. That's the cleanest way, and those are made to do that. It just requires a bit more puzzling.

      – Joris Meys
      Feb 10 '11 at 8:56












    • Thanks. It is definitely puzzling. Though it does what I need, there's a lot in that code I don't yet understand.

      – Aaron
      Feb 10 '11 at 15:18












    • 5





      thanks for your edit showing how to get both the result and the warning; however, the function is called twice when there's a warning. Can it be done with only one call (in case the function is slow, for example)?

      – Aaron
      Feb 10 '11 at 2:17











    • @Aaron : then I'd go for the handlers as shown below by you. That's the cleanest way, and those are made to do that. It just requires a bit more puzzling.

      – Joris Meys
      Feb 10 '11 at 8:56












    • Thanks. It is definitely puzzling. Though it does what I need, there's a lot in that code I don't yet understand.

      – Aaron
      Feb 10 '11 at 15:18







    5




    5





    thanks for your edit showing how to get both the result and the warning; however, the function is called twice when there's a warning. Can it be done with only one call (in case the function is slow, for example)?

    – Aaron
    Feb 10 '11 at 2:17





    thanks for your edit showing how to get both the result and the warning; however, the function is called twice when there's a warning. Can it be done with only one call (in case the function is slow, for example)?

    – Aaron
    Feb 10 '11 at 2:17













    @Aaron : then I'd go for the handlers as shown below by you. That's the cleanest way, and those are made to do that. It just requires a bit more puzzling.

    – Joris Meys
    Feb 10 '11 at 8:56






    @Aaron : then I'd go for the handlers as shown below by you. That's the cleanest way, and those are made to do that. It just requires a bit more puzzling.

    – Joris Meys
    Feb 10 '11 at 8:56














    Thanks. It is definitely puzzling. Though it does what I need, there's a lot in that code I don't yet understand.

    – Aaron
    Feb 10 '11 at 15:18





    Thanks. It is definitely puzzling. Though it does what I need, there's a lot in that code I don't yet understand.

    – Aaron
    Feb 10 '11 at 15:18













    22














    On the R-help mailing list (see http://tolstoy.newcastle.edu.au/R/help/04/06/0217.html), Luke Tierney wrote:



    "If you want to write a function that computes a value and collects all
    warning you could do it like this:



    withWarnings <- function(expr) 
    myWarnings <- NULL
    wHandler <- function(w)
    myWarnings <<- c(myWarnings, list(w))
    invokeRestart("muffleWarning")

    val <- withCallingHandlers(expr, warning = wHandler)
    list(value = val, warnings = myWarnings)






    share|improve this answer




















    • 1





      is <<- correct?

      – isomorphismes
      Nov 11 '11 at 10:44






    • 4





      Yup, that way it updates the myWarnings outside the function; otherwise it makes a new myWarnings inside the function and the outside one doesn't get updated.

      – Aaron
      Nov 11 '11 at 16:33















    22














    On the R-help mailing list (see http://tolstoy.newcastle.edu.au/R/help/04/06/0217.html), Luke Tierney wrote:



    "If you want to write a function that computes a value and collects all
    warning you could do it like this:



    withWarnings <- function(expr) 
    myWarnings <- NULL
    wHandler <- function(w)
    myWarnings <<- c(myWarnings, list(w))
    invokeRestart("muffleWarning")

    val <- withCallingHandlers(expr, warning = wHandler)
    list(value = val, warnings = myWarnings)






    share|improve this answer




















    • 1





      is <<- correct?

      – isomorphismes
      Nov 11 '11 at 10:44






    • 4





      Yup, that way it updates the myWarnings outside the function; otherwise it makes a new myWarnings inside the function and the outside one doesn't get updated.

      – Aaron
      Nov 11 '11 at 16:33













    22












    22








    22







    On the R-help mailing list (see http://tolstoy.newcastle.edu.au/R/help/04/06/0217.html), Luke Tierney wrote:



    "If you want to write a function that computes a value and collects all
    warning you could do it like this:



    withWarnings <- function(expr) 
    myWarnings <- NULL
    wHandler <- function(w)
    myWarnings <<- c(myWarnings, list(w))
    invokeRestart("muffleWarning")

    val <- withCallingHandlers(expr, warning = wHandler)
    list(value = val, warnings = myWarnings)






    share|improve this answer













    On the R-help mailing list (see http://tolstoy.newcastle.edu.au/R/help/04/06/0217.html), Luke Tierney wrote:



    "If you want to write a function that computes a value and collects all
    warning you could do it like this:



    withWarnings <- function(expr) 
    myWarnings <- NULL
    wHandler <- function(w)
    myWarnings <<- c(myWarnings, list(w))
    invokeRestart("muffleWarning")

    val <- withCallingHandlers(expr, warning = wHandler)
    list(value = val, warnings = myWarnings)







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Feb 9 '11 at 16:19









    AaronAaron

    30.7k4 gold badges59 silver badges116 bronze badges




    30.7k4 gold badges59 silver badges116 bronze badges










    • 1





      is <<- correct?

      – isomorphismes
      Nov 11 '11 at 10:44






    • 4





      Yup, that way it updates the myWarnings outside the function; otherwise it makes a new myWarnings inside the function and the outside one doesn't get updated.

      – Aaron
      Nov 11 '11 at 16:33












    • 1





      is <<- correct?

      – isomorphismes
      Nov 11 '11 at 10:44






    • 4





      Yup, that way it updates the myWarnings outside the function; otherwise it makes a new myWarnings inside the function and the outside one doesn't get updated.

      – Aaron
      Nov 11 '11 at 16:33







    1




    1





    is <<- correct?

    – isomorphismes
    Nov 11 '11 at 10:44





    is <<- correct?

    – isomorphismes
    Nov 11 '11 at 10:44




    4




    4





    Yup, that way it updates the myWarnings outside the function; otherwise it makes a new myWarnings inside the function and the outside one doesn't get updated.

    – Aaron
    Nov 11 '11 at 16:33





    Yup, that way it updates the myWarnings outside the function; otherwise it makes a new myWarnings inside the function and the outside one doesn't get updated.

    – Aaron
    Nov 11 '11 at 16:33











    6














    here is an example:



    testit <- function() warning("testit") # function that generates warning.

    assign("last.warning", NULL, envir = baseenv()) # clear the previous warning

    testit() # run it

    if(length(warnings())>0) # or !is.null(warnings())
    print("something happened")



    maybe this is somehow indirect, but i don't know the more straightforward way.






    share|improve this answer

























    • Although this is inelegant, it's good because I can't find any other way to catch a warning and nevertheless return the normal result from the function. That is, if testit() returns a value, catching a warning with tryExcept means you lose the value. Unless I'm missing something?

      – Alex Holcombe
      Oct 22 '10 at 4:43






    • 1





      @Alex : you could do pretty easily using a tryCatch formula. You can do something with the warning in the argument, eg: warning=function(w) ...do something ... return(normal result)

      – Joris Meys
      Feb 4 '11 at 10:29











    • @Joris: I couldn't get tryCatch to return the normal result. Am I missing something? I did find a way using withCallingHandlers, from the R mailing list (included as a separate answer).

      – Aaron
      Feb 9 '11 at 16:21











    • @Aaron : see edit in my answer

      – Joris Meys
      Feb 9 '11 at 22:33











    • @AlexHolcombe You could also set options(warn=1) in which case the warnings are printed to stdout rather than stderr.

      – isomorphismes
      Nov 11 '11 at 9:30















    6














    here is an example:



    testit <- function() warning("testit") # function that generates warning.

    assign("last.warning", NULL, envir = baseenv()) # clear the previous warning

    testit() # run it

    if(length(warnings())>0) # or !is.null(warnings())
    print("something happened")



    maybe this is somehow indirect, but i don't know the more straightforward way.






    share|improve this answer

























    • Although this is inelegant, it's good because I can't find any other way to catch a warning and nevertheless return the normal result from the function. That is, if testit() returns a value, catching a warning with tryExcept means you lose the value. Unless I'm missing something?

      – Alex Holcombe
      Oct 22 '10 at 4:43






    • 1





      @Alex : you could do pretty easily using a tryCatch formula. You can do something with the warning in the argument, eg: warning=function(w) ...do something ... return(normal result)

      – Joris Meys
      Feb 4 '11 at 10:29











    • @Joris: I couldn't get tryCatch to return the normal result. Am I missing something? I did find a way using withCallingHandlers, from the R mailing list (included as a separate answer).

      – Aaron
      Feb 9 '11 at 16:21











    • @Aaron : see edit in my answer

      – Joris Meys
      Feb 9 '11 at 22:33











    • @AlexHolcombe You could also set options(warn=1) in which case the warnings are printed to stdout rather than stderr.

      – isomorphismes
      Nov 11 '11 at 9:30













    6












    6








    6







    here is an example:



    testit <- function() warning("testit") # function that generates warning.

    assign("last.warning", NULL, envir = baseenv()) # clear the previous warning

    testit() # run it

    if(length(warnings())>0) # or !is.null(warnings())
    print("something happened")



    maybe this is somehow indirect, but i don't know the more straightforward way.






    share|improve this answer













    here is an example:



    testit <- function() warning("testit") # function that generates warning.

    assign("last.warning", NULL, envir = baseenv()) # clear the previous warning

    testit() # run it

    if(length(warnings())>0) # or !is.null(warnings())
    print("something happened")



    maybe this is somehow indirect, but i don't know the more straightforward way.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Oct 11 '10 at 2:46









    kohskekohske

    54.8k7 gold badges148 silver badges147 bronze badges




    54.8k7 gold badges148 silver badges147 bronze badges















    • Although this is inelegant, it's good because I can't find any other way to catch a warning and nevertheless return the normal result from the function. That is, if testit() returns a value, catching a warning with tryExcept means you lose the value. Unless I'm missing something?

      – Alex Holcombe
      Oct 22 '10 at 4:43






    • 1





      @Alex : you could do pretty easily using a tryCatch formula. You can do something with the warning in the argument, eg: warning=function(w) ...do something ... return(normal result)

      – Joris Meys
      Feb 4 '11 at 10:29











    • @Joris: I couldn't get tryCatch to return the normal result. Am I missing something? I did find a way using withCallingHandlers, from the R mailing list (included as a separate answer).

      – Aaron
      Feb 9 '11 at 16:21











    • @Aaron : see edit in my answer

      – Joris Meys
      Feb 9 '11 at 22:33











    • @AlexHolcombe You could also set options(warn=1) in which case the warnings are printed to stdout rather than stderr.

      – isomorphismes
      Nov 11 '11 at 9:30

















    • Although this is inelegant, it's good because I can't find any other way to catch a warning and nevertheless return the normal result from the function. That is, if testit() returns a value, catching a warning with tryExcept means you lose the value. Unless I'm missing something?

      – Alex Holcombe
      Oct 22 '10 at 4:43






    • 1





      @Alex : you could do pretty easily using a tryCatch formula. You can do something with the warning in the argument, eg: warning=function(w) ...do something ... return(normal result)

      – Joris Meys
      Feb 4 '11 at 10:29











    • @Joris: I couldn't get tryCatch to return the normal result. Am I missing something? I did find a way using withCallingHandlers, from the R mailing list (included as a separate answer).

      – Aaron
      Feb 9 '11 at 16:21











    • @Aaron : see edit in my answer

      – Joris Meys
      Feb 9 '11 at 22:33











    • @AlexHolcombe You could also set options(warn=1) in which case the warnings are printed to stdout rather than stderr.

      – isomorphismes
      Nov 11 '11 at 9:30
















    Although this is inelegant, it's good because I can't find any other way to catch a warning and nevertheless return the normal result from the function. That is, if testit() returns a value, catching a warning with tryExcept means you lose the value. Unless I'm missing something?

    – Alex Holcombe
    Oct 22 '10 at 4:43





    Although this is inelegant, it's good because I can't find any other way to catch a warning and nevertheless return the normal result from the function. That is, if testit() returns a value, catching a warning with tryExcept means you lose the value. Unless I'm missing something?

    – Alex Holcombe
    Oct 22 '10 at 4:43




    1




    1





    @Alex : you could do pretty easily using a tryCatch formula. You can do something with the warning in the argument, eg: warning=function(w) ...do something ... return(normal result)

    – Joris Meys
    Feb 4 '11 at 10:29





    @Alex : you could do pretty easily using a tryCatch formula. You can do something with the warning in the argument, eg: warning=function(w) ...do something ... return(normal result)

    – Joris Meys
    Feb 4 '11 at 10:29













    @Joris: I couldn't get tryCatch to return the normal result. Am I missing something? I did find a way using withCallingHandlers, from the R mailing list (included as a separate answer).

    – Aaron
    Feb 9 '11 at 16:21





    @Joris: I couldn't get tryCatch to return the normal result. Am I missing something? I did find a way using withCallingHandlers, from the R mailing list (included as a separate answer).

    – Aaron
    Feb 9 '11 at 16:21













    @Aaron : see edit in my answer

    – Joris Meys
    Feb 9 '11 at 22:33





    @Aaron : see edit in my answer

    – Joris Meys
    Feb 9 '11 at 22:33













    @AlexHolcombe You could also set options(warn=1) in which case the warnings are printed to stdout rather than stderr.

    – isomorphismes
    Nov 11 '11 at 9:30





    @AlexHolcombe You could also set options(warn=1) in which case the warnings are printed to stdout rather than stderr.

    – isomorphismes
    Nov 11 '11 at 9:30











    1














    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.






    share|improve this answer































      1














      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.






      share|improve this answer





























        1












        1








        1







        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.






        share|improve this answer















        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 27 at 11:51

























        answered Mar 27 at 11:35









        Tom GreenwoodTom Greenwood

        1057 bronze badges




        1057 bronze badges






























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3903157%2fhow-can-i-check-whether-a-function-call-results-in-a-warning%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript