if( !require('investr') ){ install.packages('investr', dependencies=TRUE, repos='http://cran.rstudio.com/') } library(investr) # has the function plotFit library(MASS) data(wtloss) plot(wtloss$Days, wtloss$Weight, xlab='Days', ylab='Weight') grid() # Build a self-starter function for this model: # shiftedExpModel = function(predictor, b, y0, c){ y0 * exp(predictor/b) + c } shiftedExpModelInit = function(mCall, LHS, data){ xy = sortedXyData(mCall[['predictor']], LHS, data) n = dim(xy)[1] c = xy[n,'y'] - 1 # this makes y - c = 1 when y is the last (sorted according to x) value xy[,'y'] = xy[,'y']- c lmFit = lm(log(xy[,'y']) ~ xy[,'x']) coefs = coef(lmFit) y0 = exp(coefs[1]) b = 1/coefs[2] value = c(b, y0, c) names(value) = mCall[c('b','y0','c')] value } shiftedExpModelSS = selfStart(shiftedExpModel, shiftedExpModelInit, c('b','y0','c')) # Fit our model to the given data: # wtloss.m1 = nls(Weight ~ shiftedExpModelSS(Days, b, y0, c), data=wtloss, trace=FALSE) print(summary(wtloss.m1)) #postscript("../../WriteUp/Graphics/Chapter3/chap_3_prob_3.eps", onefile=FALSE, horizontal=FALSE) plotFit(wtloss.m1, main='wtloss data and fit') grid() #dev.off()