# [R] fit a deterministic function to observed data

Gabor Grothendieck ggrothendieck at gmail.com
Mon Apr 19 15:09:59 CEST 2010

```Plotting y vs. x:

plot(y ~ x)

the graph seems to be flattening out at x = 0 at a level of around y =
500 so lets look at:

plot(500-y ~ x)

This curve is moving up rapidly so lets take the log to flatten it out:

plot(log(500-y) ~ x)

That looks quite linear so log(500-y) = A + B * x and solving:

y = 500 - exp(A + B*x)

The 500 was a just a ballpark so lets make that a parameter too:

y = C - exp(A + B*x) = C - exp(A) * exp(B*x) = C + D * exp(B*x)

where we have replaced -exp(A) with D.

Fitting this gives:

> fm <- nls(y ~ cbind(1, exp(B * x)), start = c(B = 1), alg = "plinear"); fm
Nonlinear regression model
model:  y ~ cbind(1, exp(B * x))
data:  parent.frame()
B    .lin1    .lin2
0.1513 498.9519  -5.1644
residual sum-of-squares: 627.6

Number of iterations to convergence: 6
Achieved convergence tolerance: 6.192e-06

> # graphing
> plot(y ~ x, pch = 20, col = "red")
> lines(fitted(fm) ~ x)
> title("y = 498.9519 - 5.1644 * exp(0.1513 * x)")

On Mon, Apr 19, 2010 at 8:42 AM, vincent laperriere
<vincent_laperriere at yahoo.fr> wrote:
> Hi all,
>
> I am not a mathematician and I am trying to fit a function which could fit my observed data.
> Which function should I use and how could I fit it to data in R?
> Below are the data:
> x <- c(0, 9, 17, 24, 28, 30)
> y <- c(500, 480, 420, 300, 160, 5)
>
> I use R for Mac OS, version 2.10-1 2009-08-24
> Thank you for your help.
>
> Vincent.
>
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help