[R] Finding the first value without warning in a loop

David Winsemius dwinsemius at comcast.net
Sun Dec 7 17:27:36 CET 2008


Have you considered instead sending the warnings to someplace where it  
won't bother the user? If so then sink() might be useful.

My reading of the help page suggests that your call to suppressWarnigs  
is storing any results outside the Global environment. This is what I  
came up with. It may not be as general as you may want, since it only  
detects one kind of warned event, a NaN result.

testit <- function(a)
{ options(warn=-1)
repeat
    {z=log(a)
     a=a+ 0.1
     if(!is.nan(z) || a > 5 )
           {options(warn=0);   return(a); break }
}   }

 > testit(-3)
[1] 0.1

-- 
David Winsemius

On Dec 7, 2008, at 2:38 AM, Andreas Wittmann 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.



More information about the R-help mailing list