0

I have a large dataset where i need to do NLS estimation on different segments of the data.

I want to loop trough the data, but the NLS function i have specified and sometimes creates and error (which is logical when u look at the data).

However, is there a way just to move on if NLS produces an error? (or specify another function if the first function is too complex?)

  • Good practice would be to add a case to your function where it accounts for these errors. – GooJ Oct 27 '19 at 21:42

2 Answers2

1

A simple example to continue to loop despite facing an error in the loop is using try and catch, shown below:

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Error, but continue!")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

Output

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Error, but continue! 
[1] 8
[1] 9
[1] 10
ashwin agrawal
  • 1,603
  • 8
  • 16
1

You might want to look at purrr's wrappers for capturing side effects.

Example of a failing loop:

for(x in list(10, "a", 1)) {
  res <- log(x)
  print(res)
}

#> x =  10 ; result:  2.302585 
#> Error in log(x) : non-numeric argument to mathematical function

Loop moves on:

library(purrr)
possibly_log <- possibly(log, otherwise = NA)

for(x in list(10, "a", 1)) {
  res <- possibly_log(x)
  cat("x = ", x, "; result: ", res, "\n")
}

#> x =  10 ; result:  2.302585 
#> x =  a ; result:  NA 
#> x =  1 ; result:  0 
Iaroslav Domin
  • 2,698
  • 10
  • 19