[R] how to trap any warnings from an R function -- again :(

Boryeu Mao B.Mao at cerep.com
Thu May 2 03:00:49 CEST 2002


With the incorporation of the useful hints, my user function now looks like
this:

userfn <- function() {
  ...
ow <- options("warn")
options(warn = 2);
  ...
reg<-try(polr(act~.,data=mm,Hess=TRUE))
  ...
sumreg<-try(summary(reg))
print(length(sumreg))
print(sumreg)
  ...
options(ow) # reset

}

The routine userfn() is called multiple times, two of which I happen to know
to have warnings about NaNs being produced.  However, only once was the
condition caught, with the following output from the print statements:

[1] 1
[1] "Error in sqrt(diag(vc)) : (converted from warning) NaNs produced\n"
attr(,"class")
[1] "try-error"

The other time (the second time in fact), the length of sumreg was 16 (that
for a normal summary), and the printed sumreg actually shows NaN's in the
coefficients, without any printed error message as that in the 1st instance.
Where do I look to see why any error should escape?


-----Original Message-----
From: Prof Brian D Ripley [mailto:ripley at stats.ox.ac.uk]
Sent: Tuesday, April 30, 2002 10:00 AM
To: Boryeu Mao
Cc: 'Jason Turner'; r-help at stat.math.ethz.ch
Subject: RE: [R] how to trap any warnings from an R function


On Tue, 30 Apr 2002, Boryeu Mao wrote:

> Thanks for the reply.  The problem that I have in a nutshell is the
> following:
>
> usertest <- function {
>  ...
>  reg<-polr(act~., data=mm)
>  summary(reg)
>  return(reg$AIC)
>  }
>
> For some data, NaN's are produced (in sqrt(diag(vc))), and I'd like to
trap
> this condition and any other warnings, so that a negative value, say, can
be
> returned to the calling function to indicate the warning condition.
> Warnings from
> summary() are produced and placed in 'last.warning' but that is accessible
> only at the top-level, not within usertest(); I've tried setting 'warn' in
> options() but hadn't found a way to do this.  I'm still searching various
> docs for any ideas, and it seems to be something that might be quite
> straightforward.  Any points/ideas are appreciated.   Thanks!

To exmpand Jason's suggestion:

options(warn=2)
try(summary(reg))

should do this.  But of course you can test the condition directly, as
it will be in the object returned by summary(reg) (which in your code
sample does nothing useful, as it will not be auto-printed).


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list