[R] how to compute maximum of fitted polynomial?

Bert Gunter gunter.berton at gene.com
Wed Jun 5 01:20:05 CEST 2013


1. This looks like a homework question. We should not do homework here.

2. optim() will only approximate the max.

3. optim() is not the right numerical tool for this anyway. optimize() is.

4. There is never a guarantee numerical methods will find the max.

5. This can (and should?) be done exactly using elementary math rather
than numerical methods.

Cheers,
Bert

On Tue, Jun 4, 2013 at 2:51 PM, Rui Barradas <ruipbarradas at sapo.pt> wrote:
> Hello,
>
> As for the first question, you can use ?optim to compute the maximum of a
> function. Note that by default optim minimizes, to maximize you must set the
> parameter control$fnscale to a negative value.
>
> fit <- lm(y ~ poly(x, 3))
>
> fn <- function(x, coefs) as.numeric(c(1, x, x^2, x^3) %*% coefs)
>
> sol <- optim(0, fn, gr = NULL, coef(fit), control = list(fnscale = -1),
>         method = "L-BFGS-B", lower = 0, upper = 1)
>
>
> As for the second question, I believe you can do something like
>
> dfdx <- D( expression(a + b*x + c*x^2 + d*x^3), "x")
>
> a <- coef(fit)[1]
> b <- coef(fit)[2]
> c <- coef(fit)[3]
> d <- coef(fit)[4]
> x <- sol$par
> eval(dfdx)
>
>
> See the help page for ?D
>
>
> Hope this helps,
>
> Rui Barradas
>
> Em 04-06-2013 21:32, Joseph Clark escreveu:
>>
>> My script fits a third-order polynomial to my data with something like
>> this:
>>
>> model <- lm( y ~ poly(x, 3) )
>>
>> What I'd like to do is find the theoretical maximum of the polynomial
>> (i.e. the x at which "model" predicts the highest y).  Specifically, I'd
>> like to predict the maximum between 0 <= x <= 1.
>>
>> What's the best way to accomplish that in R?
>>
>> Bonus question: can R give me the derivative or 2nd derivative of the
>> polynomial?  I'd like to be able to compute these at that maximum point.
>>
>> Thanks in advance!
>>
>>
>> // joseph w. clark , phd , visiting research associate
>> \\ university of nebraska at omaha - college of IS&T
>> ______________________________________________
>> R-help at r-project.org mailing list
>> 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.
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm



More information about the R-help mailing list