[R] nls & optimize

Muhammad Rahiz muhammad.rahiz at ouce.ox.ac.uk
Tue Oct 19 11:44:59 CEST 2010


Hi all,

I'm plotting to get the intersection value of three curves. Defining 
the x-axis as dsm, the following code works;

dsm = c(800,600,NA,525,NA,450,400,NA,NA,NA,0)
s3 = seq(0.05,1.05,0.1)

plot(dsm,s3,col="blue",las=1,ylab="fraction",xlab="distance (km)")

fc <- function(x,a,b){a*exp(-b*x)}
fm <- nls(s3~fc(dsm,a,b),start=c(a=1,b=0))
co <- coef(fm)
curve(fc(x,a=co[1],b=co[2]),add=TRUE,col="black",lwd=1)

r <- range(dsm,na.rm=TRUE)
n <- 1/2.71
val <- optimize(f=function(x) abs(fc(x,a=co[1],b=co[2])-n),c(r[1],r[2]))

abline(v=val$minimum,lty=2,col="blue",lwd=1)
abline(h=n,lty=2,col="red",lwd=1)
text(100,0.1,paste(round(val$minimum,2),"km",sep=" "))

When I flip the axes, i.e. x-axis = s3, and change the nls start up value 
to a=800, the three curves does not intersect.

dsm = c(800,600,NA,525,NA,450,400,NA,NA,NA,0)
s3 = seq(0.05,1.05,0.1)

plot(s3,dsm,col="blue",las=1,xlab="fraction",ylab="distance (km)")

fc <- function(x,a,b){a*exp(-b*x)}
fm <- nls(dsm~fc(s3,a,b),start=c(a=800,b=0))
co <- coef(fm)
curve(fc(x,a=co[1],b=co[2]),add=TRUE,col="black",lwd=1)

r <- range(dsm,na.rm=TRUE)
n <- 1/2.71
val <- optimize(f=function(x) abs(fc(x,a=co[1],b=co[2])-n),c(r[1],r[2]))

abline(h=val$minimum,lty=2,col="blue",lwd=1)
abline(v=n,lty=2,col="red",lwd=1)
text(100,0.1,paste(round(val$minimum,2),"km",sep=" "))

It's merely reversing the axes - the code should work, shouldn't it?
Any suggestions why this happens and how I can correct it?

Thanks.

Muhammad



More information about the R-help mailing list