# [R] LOESS function Newton optimization

David Winsemius dwinsemius at comcast.net
Sun Nov 13 14:26:00 CET 2011

```On Jul 12, 2011, at 7:53 PM, KenjiPsyD wrote:

> I have a question about running an optimization function on an
> existing LOESS
> function defined in R. I have a very large dataset (1 million
> observations)
> and have run a LOESS regression. Now, I want to run a Newton-Raphson
> optimization to determine the point at which the slope change is the
> greatest.
>
> I am relatively new to R and have tried several permutations of the
> maxNR
> and nlm functions with no success. For example, I used the nlm
> function as
> follows:
>
> LOESS <- loess(Y ~ X)
> optim <- nlm(function(x) LOESS(x))...

I don't see how that would be examining slopes.

>
> However, this doesn't seem to work. In the examples I see online, the
> function in nlm and maxNR are user defined, instead of the output of
> another
> function (i.e., my LOESS regression).
>
> Is it possible to run this type of optimization function on my Loess
> function?

> cars.lo <- loess(dist ~ speed, cars)
> is.function( cars.lo)
 FALSE

If you want to make it a function, there is approxfun in the stats
package.

car.fun <- approxfun(x=cars.lo\$x, cars.lo\$fitted)
plot(dist~speed, data=cars)

Some functions require that a function be offered that takes x as its
argument.

> car.fun(x=5)
Error in car.fun(x = 5) : unused argument(s) (x = 5)

If that is the case with your optimization routine then you can create
one with:

> car.funx <- function(x) car.fun(x)
> car.funx(x=5)
 8.095681

--

David Winsemius, MD
West Hartford, CT

```