One way will be to solve this as an ordinary optimization problem with
an equality constraint. Function `alabama::auglag` can do this:

    library(alabama)
    fn <- function(p) sum((df$y - p[1]*exp(-p[2]*df$x))^2)
    heq <- function(p) sum(p[1]*exp(-p[2]*df$x)) - 5

    # Start with initial values near first solution
    sol <- auglag(c(4, 4), fn=fn, heq=heq)

Solution with myfit:    4.134    4.078
Solution with auglag:   4.126763 4.017768

The equality constraint is still fulfilled:

    a <- sol$par[1]; lambda <- sol$par[2]
    sum(a*exp(-lambda*df$x))
    ## [1] 5

Plot the differences of these two solutions:

    plot(df$x, a*exp(-lambda*df$x) - predict(myfit), type='l')

Interestingly, the difference between 5 and `predict(myfit)` is *not*
just evenly spread across all 15 points.

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to