On 12/06/2014 02:53 PM, ce wrote:
Dear all,

Let's say I have this script , below. tryCatch  indeed catches the error but 
exists, I want function to continue and stay in the loop. I found very  
examples of withRestarts on internet to figure it out. Could you help me how to 
do it ?


myfunc <- function()
{
   while(1)
   {
   x <- runif(1)
   if ( x > 0.3 ) a <-  x/2 else a <- x/"b"
   print(a)
   Sys.sleep(1)
   }
}

Hi --

Modify your function so that the code that you'd like to restart after is surrounded with withRestarts(), and with a handler that performs the action you'd like, so

myfunc <- function()
{
    while(TRUE)
    {
        x <- runif(1)
        withRestarts({
            if ( x > 0.3 ) a <-  x/2 else a <- x/"b"
            print(a)
        }, restartLoop = function() {
            message("restarting")
            NULL
        })
        Sys.sleep(1)
    }
}

Instead of using tryCatch(), which returns to the top level context to evaluate the handlers, use withCallingHandlers(), which retains the calling context. Write a handler that invokes the restart

withCallingHandlers({
    myfunc()
}, error = function(e) {
    message("error")
    invokeRestart("restartLoop")
})

It's interesting that tryCatch is usually used with errors (because errors are hard to recover from), and withCallingHandlers are usually used with warnings (because warnings can usually be recovered from), but tryCatch() and withCallingHandlers() can be used with any condition.

Martin


tryCatch({ myfunc() },
         warning = function(w) { print("warning") },
         error = function(e) { print("error") },
         finally = {  print("end") }
)

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



--
Computational Biology / Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N.
PO Box 19024 Seattle, WA 98109

Location: Arnold Building M1 B861
Phone: (206) 667-2793

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to