Skip to content
Back to formatted view

Raw Message

Message-ID: <971536df0812070921u3e8dd78w11c169bb67b45354@mail.gmail.com>
Date: 2008-12-07T17:21:11Z
From: Gabor Grothendieck
Subject: Finding the first value without warning in a loop
In-Reply-To: <493B7D91.7020309@gmx.de>

Try this:

for (x in c(-2, 2, 4)) {
	tryCatch({
		y <- log(x)
		xx <- x
		break
	}, warning = function(w) {})
}
print(xx) # 2



On Sun, Dec 7, 2008 at 2:38 AM, Andreas Wittmann
<andreas_wittmann at gmx.de> wrote:
> Dear R useRs,
>
> with the following piece of code i try to find the first value which can be
> calculated without warnings
>
> `test` <- function(a)
> {
>  repeat
>  {
>   ## hide warnings
>   suppressWarnings(log(a))
>
>   if (exists("last.warning", envir = .GlobalEnv))
>   {
>     a <- a + 0.1
>     ## clear existing warnings
>     rm("last.warning", envir = .GlobalEnv)
>   }
>
>  if(a > 5 || !exists("last.warning", envir = .GlobalEnv))
>   break
>  }
>
>  return(a)
> }
>
> if i run this with test(-3), i would expect a=0 as return value.
> Is it also possible to hide warnings during my function, i guess i use
> suppressWarnings in a wrong way here?
>
> Thanks and best regards
>
> Andreas
>
> ______________________________________________
> 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.
>