ODE solver
Using options(warn=2) is the easiest way to get this function to stop when
it makes the warning, but it will stop at any warning, not just the one you
are worried about. You can use withCallingHandlers() or tryCatch() to be
more selective. E.g., the following will stop on any warning that has "time"
in the warning message but willl print the warning message and continue
for other warnings.
catchTimeWarning <- function(expr) {
withCallingHandlers(expr,
warning=function(e){
warningMsg <- conditionMessage(e)
if (grepl("time", warningMsg)) {
stop(warningMsg)
} else {
message(warningMsg)
invokeRestart("muffleWarning")
}
}
)
}
Here is an example of using it
f <- function (n)
{
# naive way to compute factorial
if (n < 1 || n != round(n)) {
warning("This will take a very long time")
}
fac <- n
while ((n <- n - 1) != 0) {
fac <- fac * n
}
if (is.infinite(fac)) {
warning("Factorial calculation overflowed")
}
fac
}
catchTimeWarning(f(5))
[1] 120
catchTimeWarning(f(1000))
Factorial calculation overflowed [1] Inf
catchTimeWarning(f(-1.5))
Error in function (e) : This will take a very long time Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com
-----Original Message----- From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of David Winsemius Sent: Thursday, May 02, 2013 7:22 AM To: Tjun Kiat Teo Cc: r-help at r-project.org Subject: Re: [R] ODE solver On May 2, 2013, at 1:36 AM, Tjun Kiat Teo wrote:
I am trying to use the package ode and periodically it will come up with this error message Warning..Internal T (=R1) and H (=R2) are such that in the machine, T + H = T on the next step (H = step size). Solver will continue anyway. And then the program just take very long to run. Is there anyway to get the program to terminate when this warning is issued instead of continuing to run ?
Standard debugging strategy: You set option to terminate when a warning is issued: options(warn=2) ?options # And especially review the examples You can also arrange for R to drop back into the browser(): ?browser -- David Winsemius Alameda, CA, USA
______________________________________________ R-help at r-project.org mailing list 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.