# [R] picewise function in nls....

akshay kulkarni @k@h@y_e4 @end|ng |rom hotm@||@com
Fri Apr 19 12:12:06 CEST 2019

```dear Ivan,
THanks for the reply......But what do you mean by "since fx does not depend on any of the parameters you
optimize in the nls() call."? Can you give an example?

very many thanks for your time and effort.....
Yours sincerely,

AKSHAY M KULKARNI

________________________________
From: Ivan Krylov <krylov.r00t using gmail.com>
Sent: Thursday, April 18, 2019 4:50 PM
To: akshay kulkarni
Cc: R help Mailing list
Subject: Re: [R] picewise function in nls....

On Thu, 18 Apr 2019 10:36:10 +0000
akshay kulkarni <akshay_e4 using hotmail.com> wrote:

> fx <-   (x1 <= -2)*(x1^2) + (x1 > -2 && x1 < 2)*(x1^3) + (x1 > =
> 2)*(x1^4)
>
> Can I include fx in an nls call  to create something like this:
>
> NLS1 <- nls(y ~ a*(sin(x2) + fx), start = list(a = 2))   ?

For now, you can, since fx does not depend on any of the parameters you
optimize in the nls() call. (Actually, the model as presented should be
solveable by lm(y ~ I(sin(x2) + fx) + 0), since it is linear in its
only parameter.)

If you make fx a function and use ifelse() to provide different
outcomes depending on a condition in a vectorized fashion, you would
make it easier to add new parameters later, should the need arise:

fx <- function(x1, x2)
ifelse(x1 <= -2, EXPR_IF_TRUE..., EXPR_IF_FALSE...)

NLS1 <- nls(y ~ a*(sin(x2) + fx(x1, x2)), ...)

--
Best regards,
Ivan

[[alternative HTML version deleted]]

```