Gabriel123
Gabriel123

Reputation: 456

Skip occasional error in loop

I am aware that the "skip error in for loop" has been answered multiple times (see How to skip an error in a loop or Skip Error and Continue Function in R). But all answers are complex and difficult to apply to a different situation for a novice.

I am performing a Gaussian histogram fitting on 100's of datasets using a piece of code.

results = list()
for(i in 1:length(T_files)){
  R = Table[i][,1]
  tab = data.frame(x = seq_along(R), r = R)
  res = nls(R ~ k*exp(-1/2*(x-mu)^2/sigma^2), start=c(mu=15,sigma=5, k=1) , data = tab)
  v = summary(res)$parameters[,"Estimate"]
  fun = function(x) v[3]*exp(-1/2*(x-v[1])^2/v[2]^2) 
  results[[i]] = fun(seq(0, 308, 1))/max(fun_SP(seq(0, 308, 1)))/2
}

The code works on most datasets when tested on each individual. However, the loop does not and shows the "error in nls(...): singular gradient" message. I want to skip this message and continue to the next dataset.

I know that a tryCatch function may be used, but the line containing the nls function is complex and I have not found a way to use correctly tryCatch in this line. Any advice is welcome :-)

Upvotes: 3

Views: 610

Answers (1)

Henry Navarro
Henry Navarro

Reputation: 953

Use the function try, it allows you save an error and then put a condition if(error==T) then "pass to next df". Something like this:

error<-try(your code...)
if(class(error)!="try-error"){pass to the next one}

In yor case, maybe must be:

results = list()
for(i in 1:length(T_files)){
  R = Table[i][,1]
  tab = data.frame(x = seq_along(R), r = R)
  error = try(res <- nls(R ~ k*exp(-1/2*(x-mu)^2/sigma^2), start=c(mu=15,sigma=5, k=1) , data = tab))

    if(class(error)!="try-error"){
      v = summary(res)$parameters[,"Estimate"]
      fun = function(x) v[3]*exp(-1/2*(x-v[1])^2/v[2]^2) 
      results[[i]] = fun(seq(0, 308, 1))/max(fun_SP(seq(0, 308, 1)))/2
    }else{
      pass to next data frame (or something like that)
         }
}

Upvotes: 2

Related Questions