Re: [R] using integrate with optimize nested in the integration

From: Sundar Dorai-Raj <sundar.dorai-raj_at_pdf.com>
Date: Fri 29 Jul 2005 - 06:27:25 EST

Gregory Gentlemen wrote:
> Hi guys
> im having a problem getting R to numerically integrate for some function,
> say f(bhat)*optimize(G(bhat)), over bhat. Where id like to integrate this over some finite range, so that here as we integrate over bhat optimize would return a different optimum.
>
> For instance consider this simple example for which I cannot get R to return the desired result:
>
> f <- function(bhat) exp(bhat)
> g <- function(bhat) optimize(f,c(0,15),maximum=TRUE)$maximum*bhat
> integrate(g,lower=0,upper=5)
> which returns:
> 187.499393759 with absolute error < 2.1e-12
>
> However this is an approximation of : 15*(5^2/2 - 0)=187.5, not what I intended on getting. Its not identifying that f is a function of bhat ... any advice or ways I can get integrate to not treat this as a constant?
>
> Any help is appreciated.
>
> Gregoy Gentlemen
>

Hi, Gregory,

Your example is not very useful here since the optimize function is constant.

I think you want something more like:

f <- function(bhat, x) {

   exp(bhat * x)
}
g <- function(bhat) {

   o <- vector("numeric", length(bhat))
   for(i in seq(along = bhat))
     o[i] <- optimize(f, c(0,15), maximum = TRUE, x = bhat[i])$maximum    bhat * o
}
integrate(g, lower = 0, upper = 5)

Because of the way "integrate" works, "g(bhat)" will always return a vector.

HTH, --sundar



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Fri Jul 29 06:34:23 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:34:07 EST