# nllsqt1.r October 2007 # # test problem for nonlinear least squares # from Fuller (1976) # both <- matrix(scan("fulnls.dat"),12,2, byrow=TRUE) y <- both[,1] x <- both[,2] fulnls <- list(y,x) # need data frame or list print(fulnls) # see list # # nonlinear least squares # # find better starting values t1 <- y[ x==max(x)] # max value as asymptote xs <- x[ x < 2 ] # use smallest x's ys <- log( t1 - y[ x < 2 ] ) # transform reversed y's # simple linear regression t3 <- sum( (xs - mean(xs) )*ys )/ sum( (xs-mean(xs))**2 ) # slope t2 <- mean(ys)-t3*mean(xs) # intercept # transform back from log and reverse t2 <- -exp(t2) t3 <- - t3 # done -- now have better starting values c(t1,t2,t3) # # call nls using defaults + trace that1 <- nls( y ~ th1 + th2*exp(-th3*x), data=fulnls, start=list( th1=t1, th2=t2, th3=t3), trace=TRUE ) that1 thfin <- coef(that1) print("coefficients") print(thfin) # # nonlinear least squares using nl2sol that1 <- nls( y ~ th1 + th2*exp(-th3*x), data=fulnls, algorithm="port", start=list( th1=t1, th2=t2, th3=t3), trace=TRUE ) that1 # # cov matrix of coefficients print("Cov(coefficients)") vcov(that1) print("Residuals, etc.") resid(that1) sum(resid(that1)**2) # done rm(list=ls()) q()