[R] Error handling

Thomas Lumley tlumley at u.washington.edu
Tue Jun 19 23:14:48 CEST 2007


This is FAQ 7.32 How can I capture or ignore errors in a long simulation?

 	-thomas

On Tue, 19 Jun 2007, Peter Sajosi wrote:

> Hello,
>
>  I have a question about error handling. I run simulation studies and often the program stops with an error, for example during maximum likelihood. I would like the program not to stop but to continue and I would like to ask how the error handling can be set up for this (if it can). I tried to look through manuals etc but unfortunately did not get closer to the solution. Below is a small example with some numbers, where the nlm function gives an error. Is it possible to make R and the program ignore the error?
>
>  (there is a small for loop in the end of the example, which breaks - ideally the program would complete the for loop even though there are errors). Of course this is just an example, in the simulation study the error comes up quite rarely but still it is annoying to handle it manually each time.
>  Many thanks
> Peter
>
>  The example:
>  ------------
>
> logfunc <- function (params) {
>  vutil1 <- as.matrix(x2[,1:3]) %*% params
> vutil2 <- as.matrix(x2[,4:6]) %*% params
>  logl <- 0
>  for (i in 1:6) {
>  prob <- log((exp(vutil1[i])*achoices[i,1]+exp(vutil2[i])*achoices[i,2])/(exp(vutil1[i])+exp(vutil2[i])))
>  logl <- logl + prob
>  }
>  return (-logl)
>  }
>
> x2 <- array(c(0,4,1,3,5,3,3,2,1,4,1,2,0,2,2,1,1,4,1.2233310 ,0.0000000 ,0.8155540 ,0.9320617 ,1.4272195 ,1.8349965 , 0.6116655, 3.2622160, 0.8155540, 3.7282469,0.0000000 ,4.5874913 ,0.6116655,3.2622160 ,1.6311080 ,1.8641235, 4.2816586, 0.9174983),dim=c(6,6))
> achoices <- array(c(1,0,1,0,1,0,0,1,0,1,0,1),dim=c(6,2))
>  for (k in 1:5) {
>  nlm(logfunc, c (1,1,1),print.level=2)
>  }
>  ---
>  Thanks!!!
>  -------
>
>
>
>
> ---------------------------------
> Moody friends. Drama queens. Your life? Nope! - their life, your story.
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle



More information about the R-help mailing list