# [R] R formula language---a min and max function?

Gabor Grothendieck ggrothendieck at gmail.com
Tue May 4 21:57:05 CEST 2010

```You need to use set.seed first so that your example is reproducible.
Using set.seed(1) there is no error:

> set.seed(1)
> x=1:20
> y= 2+3*ifelse(x>10, 10, x)+rnorm(20,0,0.01)
> r1= nls( y~ a+b*pmin(c,x), start=list(a=2, b=3, c=10), trace=TRUE )
0.001657260 :   2  3 10
0.00153709 :  1.998312 3.000547 9.999568
0.001509616 :  1.996222 3.001117 9.998197
0.001509616 :  1.996222 3.001117 9.998197
> r1
Nonlinear regression model
model:  y ~ a + b * pmin(c, x)
data:  parent.frame()
a     b     c
1.996 3.001 9.998
residual sum-of-squares: 0.001510

Number of iterations to convergence: 3
Achieved convergence tolerance: 3.195e-09

On Tue, May 4, 2010 at 3:52 PM, ivo welch <ivo.welch at gmail.com> wrote:
> thank you, david.  indeed.  works great (almost).  an example for
> anyone else googling this in the future:
>
>> x=1:20
>> y= 2+3*ifelse(x>10, 10, x)+rnorm(20,0,0.01)
>> r1= nls( y~ a+b*pmin(c,x), start=list(a=2, b=3, c=10), trace=TRUE )
> 0.002142 :   2  3 10
> 0.002115 :   2.004  3.000 10.000
> 0.002114 :   2.006  2.999 10.001
> 0.002084 :   2.005  2.999 10.000
> ...
> 0.002079 :   2.005  2.999 10.000
> Error in nls(y ~ a + b * pmin(c, x), start = list(a = 2, b = 3, c = 10),  :
>  step factor 0.000488281 reduced below 'minFactor' of 0.000976562
>
> strange error, but unrelated to my question.  will figure this one out next.
>
> regards,
>
> /iaw
>
>
> On Tue, May 4, 2010 at 3:40 PM, David Winsemius <dwinsemius at comcast.net> wrote:
>>
>> On May 4, 2010, at 3:33 PM, ivo welch wrote:
>>
>>> Dear R experts---I would like to estimate a non-linear least squares
>>> expression that looks something like
>>>
>>>  y ~ a+b*min(c,x)
>>>
>>> where a, b, and c are the three parameters.  how do I define a min
>>> function in the formula language of R?  advice appreciated.
>>
>> ?pmin
>>
>>>
>>> sincerely,
>>>
>>> /iaw
>>>
>>> ______________________________________________
>>> R-help at r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-help
>>> http://www.R-project.org/posting-guide.html
>>> and provide commented, minimal, self-contained, reproducible code.
>>
>> David Winsemius, MD
>> West Hartford, CT
>>
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help