[R] how to include integrate in a function that can be solved with uniroot?
Gerrit Draisma
gdraisma at xs4all.nl
Mon Nov 14 11:32:54 CET 2011
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
>
========
More information about the R-help
mailing list