Search code examples
rloopsnanls

nls in for loop stops due to Error in nlsModel


If I run a for loop proceeding multiple times nlsLM() sometimes due to useless data Rstudio stops and shows the following error messenge: "Error in nlsModel(formula, mf, start, wts) : singular gradient matrix at initial parameter estimates"

So i know that not for every data set fit parameters can be estimated, but what I don't want is, that the entire procedure stops.

If there isn't any error the coefficients are stored in result[x] - so for now I tried a lot for the aim if fitting is not possible that NA is stored in result[x] - but with no success.

xx <- c(1:10)
result <- vector("numeric")
width<- vector("numeric")
for(x in xx){
  temp <- long[ which(long$NR== x), ]
  Ytemp <- temp$Yield
  Ttemp <- temp$Treatment
  M <- nlsLM(Ytemp ~ (maximum + (minimum - maximum)/(1+exp((Ttemp- 
x0)/dx))), 
             start=list(x0=-10, dx=1))
  print(summary(M))
  result[x] <- coef(M)[1]
  width[x] <- coef(M)[2]
}

round(result, digits = 1)
round(width, digits = 2)
mean <- mean(result)
sd <- sd(result)

I would be very happy for a hint!

Matthias


Solution

  • Consider tryCatch to assign NA to your vectors for any errors in your model call:

    xx <- c(1:10)
    result <- vector("numeric")
    width<- vector("numeric")
    
    for(x in xx) {
      temp <- long[which(long$NR== x),]
      Ytemp <- temp$Yield
      Ttemp <- temp$Treatment
    
      tryCatch({
         M <- nlsLM(Ytemp ~ (maximum + (minimum - maximum)/(1+exp((Ttemp-x0)/dx))), 
                    start=list(x0=-10, dx=1))
         print(summary(M))             # PRINT MODEL SUMMARY
         result[x] <- coef(M)[1]       # ASSIGN COEF
         width[x] <- coef(M)[2]        # ASSIGN COEF
    
      }, error = function(e) {
         print(e)                      # PRINT ERROR MESSAGE
         result[x] <- NA               # ASSIGN NA
         width[x] <- NA                # ASSIGN NA
      })
    
    }
    
    round(result, digits = 1)
    round(width, digits = 2)
    mean <- mean(result, na.rm=TRUE)   # REMOVE NA
    sd <- sd(result, na.rm=TRUE)       # REMOVE NA