0

I'm quite new in R and in StackOverflow. I'm trying to make a large bootstrap using a nlsLM inside a for loop. The nlsLM must to run about 1000 or 1500 times, each loop use about 70% of my data ordered randomly. If I run my code about 100 times it works fine, but with 1000 or 1500 loops it give me an error like " Error in nlsModel(formula, mf, start, wts) : singular gradient matrix at initial parameter estimates ". I've already tried different start values, but always get the same error. Here is my code:

fitpoly2.btsp<-function(rep,s.rep) {
nsample<-round(nrow(dados)*(s.rep/100))
coefpoly2<-matrix()
for (i in 1:rep) {
    rand<-dados[sample(nrow(dados),nsample),]

    poly2fitted<-tryCatch({poly2fitted<-tryCatch({
        nlsLM(Weight ~ (a1 * Length^b1) * (1/(1 + exp(rate *(Length - scp)))) + (a2 * Length^b2) *(1 - (1/(1 + exp(rate * (Length - scp))))),data=rand,start=list(a1=0.01,b1=2.8,a2=0.02,b2=3,scp=36,rate=10),control=nls.lm.control(maxiter=1024),lower=c(0,0,0,0,0,1),upper=c(1,6,1,6,74,20),trace=TRUE)})
if (i==1){ coefpoly2<-coef(poly2fitted)
    } else {
    coefpoly2<-rbind(coefpoly2,coef(poly2fitted))}
}}    

Well, my friends, I know this problem is simple to solve and maybe my code is wrong or primitive, but I really don't know how can I fix it.

Thank you for you help and suggestions!!

Siguza
  • 21,155
  • 6
  • 52
  • 89
José Ricardo
  • 301
  • 1
  • 2
  • 7
  • What is `range(dados$Length)`?? – jlhoward Oct 06 '14 at 15:50
  • @jlhoward, sorry if don't explained well. My data frame has 2 variables: Length and Weight, each one with more then 3000 information. I used range(dados$Length) just to know the size of the column, but I think in this part of the code I don't need to use this. Thank you for the comment. – José Ricardo Oct 06 '14 at 17:27
  • You misunderstand my question: I want to know: what is the range of `dados$Length' (minimum and maximum values). – jlhoward Oct 06 '14 at 18:09
  • dados$Length goes from 26.0 to 73.6 – José Ricardo Oct 06 '14 at 18:19
  • Generally having `exp(x)` where x>0 for some combination of the parameters can cause problems. Since `rate>1` and `scp` starts at 36, `rate*(Length-scp) > 0` for some values of `Length`. Assuming you expect `Length - scp` > 0, I would restate the function in terms of `exp(-rate*(Length-scp))` and restrict `scp` to `scp < min(Length)`. – jlhoward Oct 06 '14 at 19:42
  • Thank you, @jlhoward! Now it works fine! I just change rate to -rate and everything works. How can I restrict scp to min(Length) – José Ricardo Oct 06 '14 at 19:59
  • Using `lower=...` and `upper=...`, but why would you want to do that?? Do you expect `scp` to be within the range of `Length`?? – jlhoward Oct 06 '14 at 20:04
  • Yes, because I am using two power functions multiplied by one logistic function (from 0 to 1), the scp means the length class where the first power function "turns off" and the second "turns on". – José Ricardo Oct 06 '14 at 20:09

0 Answers0