user3313391
user3313391

Reputation: 25

error with nls function in r with almost the same data

I have two tables with very similar data and I want to fit a model:

###first data
x1 <- c(0.271237802,0.253595465,0.299072793,0.355537802,  
0.335295465,0.365922793,0.476437802,0.464095465,0.482172793)  

y1 <- c(0.039937,0.044174,0.062574,0.124286,  
0.108702,0.131217,0.213418,0.216699,0.253712)

####second data
x2 <- c(0.285180641,0.289818303,0.27255962,0.373530641,  
0.356768303,0.34930962,0.463880641,0.471668303,0.46330962)

y2 <- c(0.0499,0.063764,0.05343,0.147753,  
0.14148,0.135757,0.220635,0.245013,0.236258)

####nls.model
fo1 = nls(y1~A*(x1-v)^k, start=list(A=1, v=0.15, k=1))
coef(fo1)
summary(fo1)

fo2 = nls(y2~A*(x2-v)^k, start=list(A=1, v=0.15, k=1))
coef(fo2)
summary(fo2)

####plotting data
s <- seq(from = 0, to = 1, length = 50)
plot(y1~x1, ylab = "D/D0", xlab = "LP(%)", pch = 16, xlim=c(0,0.6), ylim=c(0,0.4), col="blue")
lines(s, predict(fo1, list(x1 = s)), col = "blue")

par(new=T)

plot(y2~x2, ylab = "D/D0", xlab = "LP(%)", pch = 16, xlim=c(0,0.6), ylim=c(0,0.4), axes=F,col="red")

In the first case, the model workes well, however in the second case it failes and gives the message:

 fo2 = nls(y2~A*((x2-v)^(k)), start=list(A=1, v=0.15, k=1))
Error in numericDeriv(form[[3L]], names(ind), env) : 
  Missing value or an Infinity produced when evaluating the model 

although the data show almost a linear relationship, I want to use nls and the proposed function because linearity is not always true.
I know, that it might have something to do with the starting values, however I wasn´t able to solve this. Does anybody have a clue?

Upvotes: 0

Views: 1166

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269421

x2-v must be non-negative so try this which should avoid the errors as long as the unconstrained minimum satisfies v is less than min(x2) .

nls(y2 ~ A * pmax(x2-v, 0)^k, start = list(A = 1, v = 0.15, k = 1))

If v is not less than min(x2) at the optimum then there is a question of whether the revised model is still acceptable.

Another possibility is to constrain v to be less than min(x2) . For example:

nls(y2 ~ A * pmax(x2-v, 0)^k + 1000 * (v > min(x2)), start = list(A = 1, v = 0.15, k = 1))

or use a constrained optimization routine.

Upvotes: 2

Related Questions