Skip to content

what´s wrong with this code?

3 messages · José Manuel Gavilán Ruiz, Berwin A Turlach

#
Hello,  I  want  to  maximize  a  likelihood  function expressed as an
integral  that  can not be symbolically evaluated. I expose my problem
in a reduced form.

g<- function(x){
integrand<-function(y) {exp(-x^2)*y}
g<-integrate(integrand,0,1)
}                         
h<-function(x) log((g(x)))

g  is an object of the class function, but g(2) is a integrate object,
I can print(g(2)) an get a result, but
if I try h(2) R says is a nonnumeric argument for a mathematical
function. My goal is to maximize h.
what?s wrong?

thanks
#
G'day Jose,

On Fri, 29 Oct 2010 11:25:05 +0200
Jos? Manuel Gavil?n Ruiz <gavi at us.es> wrote:

            
R> print(g(2))
0.00915782 with absolute error < 1.0e-16

Indeed print(g(2)) gives an output, but it is obviously not just a
numeric number but something formatted, presumably based on the class
of the returned object from g(2) and the values that this object
contains.  (You may want to read up on R's way(s) to object oriented
programming).

So what does g() return?

R> str(g(2))
List of 5
 $ value       : num 0.00916
 $ abs.error   : num 1.02e-16
 $ subdivisions: int 1
 $ message     : chr "OK"
 $ call        : language integrate(f = integrand, lower = 0, upper = 1)
 - attr(*, "class")= chr "integrate"

The object is a list with several values, and class "integrate".
I guess you want to pass only the component value to h().  

R> g <- function(x){
+ integrand <- function(y) {exp(-x^2)*y}
+ integrate(integrand, 0, 1)$value}
R> g(2)
[1] 0.00915782
R> h(g(2))
[1] -0.693231

HTH,

Cheers,

	Berwin
#
G'day Jose,

On Fri, 29 Oct 2010 11:25:05 +0200
Jos? Manuel Gavil?n Ruiz <gavi at us.es> wrote:

            
Which can be done without R quite trivially.

The result of g(x) is exp(-x^2)/2.
So h(x) is -x^2-log(2), which is maximised at x=0.

Cheers,

	Berwin