[R] capturing warnings within loops, so I know the iterations where warnings occurred?

Richard Kwock richardkwock at gmail.com
Tue Sep 24 03:15:14 CEST 2013


Hi,

Check out:

https://stat.ethz.ch/pipermail/r-help/2010-December/262626.html

> demo(error.catching)
> tryCatch.W.E

mylist <- list(NULL)
mylist_warns <- list(NULL)
old.warn <- options(warn=1)

x <- c(1:5)
for (i in 1:2) {
  assign("last.warning", NULL, envir = baseenv())
  temp <- tryCatch.W.E(x[ (i:1): 5 ] )
  mylist[[i]] = temp$value
  mylist_warns[[i]] = temp$warning
}

mylist

#[[1]]
#[1] 1 2 3 4 5
#
#[[2]]
#[1] 2 3 4 5

mylist_warns

#[[1]]
#NULL
#
#[[2]]
#<simpleWarning in (i:1):5: numerical expression has 2 elements: only
the first used>


Richard

On Mon, Sep 23, 2013 at 3:36 PM, Anika Masters <anika.masters at gmail.com> wrote:
> I am running a loop.  Warnings sometimes occur, and the lop continues
> until the end.
> For each iteration of the loop, I wish to capture and "save" any
> warnings issued, so that I can tell on which iteration the warnings
> were issued.
> I tried this, but it does not work.
>
> mylist <- list(NULL)
> mylist_warns <- list(NULL)
> old.warn <- options(warn=1)
>
> x <- c(1:5)
> for (i in 1:2) {
> assign("last.warning", NULL, envir = baseenv())
> mylist[[i]] = x[ (i:1): 5 ]
> mylist_warns[[i]] = warnings()
> }
>
> mylist
> mylist_warns
>
> ______________________________________________
> 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.



More information about the R-help mailing list