Skip to content

how to include integrate in a function that can be solved with uniroot?

2 messages · Gerrit Draisma, R. Michael Weylandt

#
Hallo,
I am trying to define expectation as an integral
and use uniroot to find the distribution parameter
for a given expectation.

However I fail to understand how to define properly
the functions involved and pass the parameters correctly.

Can anyone help me out?

Thanks,
Gerrit Draisma.


This what I tried:
=======
 > # exponential density
 > g <- function(x,lambda){ lambda *exp(-lambda*x) }
 >
 > # expectation with lambda=1/10
 > integrate(f = function(x,lambda=1/10) {x*g(x,lambda)}, 0,Inf)
10 with absolute error < 6.7e-05
 >
 > # *how to write this as a function?*
 > E <- function(lambda) {
+      integrate( f = function(x,th){x*g(x,lambda)},
+      0,Inf)$Value}
 > E(1/10)
NULL
 >
 > # *how to include this function in uniroot to find lambda*
 > # *for a given expectation?*
 > mu <- 10
 > uniroot(f<-function(th){E(th)-mu},lower=1,upper=100)
Error in if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
   argument is of length zero
 >
========
#
Try this:

EV <- function(lamb){
     fnc <- function(x) x * dexp(x, lamb)
     integrate(fnc, 0, Inf)$value
}

Your problem is that there's nothing to translate th to lambda in your
code for E.

Michael
On Mon, Nov 14, 2011 at 5:32 AM, Gerrit Draisma <gdraisma at xs4all.nl> wrote: