[R] help with likelihood contour plot

Roger Peng rpeng at stat.ucla.edu
Tue Mar 18 02:31:45 CET 2003


Be careful, I don't think your loglik function is vectorized correctly. In
particular, it only works for single values of th1 and th2. If th1 or th2
are vectors, you will get a warning and the wrong answer. The problem is
the subtraction u - th1, because u is already vector.

outer() expects that the function you pass in is vectorized and will work
elementwise on arrays, not just single values.

-roger
_______________________________
UCLA Department of Statistics
rpeng at stat.ucla.edu
http://www.stat.ucla.edu/~rpeng

On Mon, 17 Mar 2003, Sundar Dorai-Raj wrote:

> 
> 
> Murray Jorgensen wrote:
> > Can some kind person point out my error here? I'm trying to set up a 
> > grid for a countour plot of a likelihood function.
> > 
> >  > u <- rnorm(20,9.5,2.5)
> >  > # sample of size 20 from N(9.5,2.5^2)
> >  > loglik <- function(th1,th2) {
> > + n <- length(u)
> > + -(n/2)*log(2*pi*th2^2)-0.5*sum((u-th1)^2/th2^2)
> > + }
> >  > x <- seq(4.5,14.5,len=50)
> >  > y <- seq(0.5,6,len=50)
> >  > f <- outer(x, y, loglik(x,y))
> > Error in match.fun(FUN) : not function, character, or symbol: "loglik(x, 
> > y)"
> > In addition: Warning message:
> > longer object length
> >         is not a multiple of shorter object length in: u - th1
> >  > loglik(9,2)
> > [1] -44.56294
> >  > is.function(loglik)
> > [1] TRUE
> > 
> > Thanks,
> > 
> > Murray
> 
> 
> Murray,
>    From ?outer:
> 
> Details:
> 
>       `FUN' must be a function (or the name of it) which expects at
>       least two arguments and which operates elementwise on arrays.
> 
> 
> Thus, use "loglik" and not "loglik(x,y)", as in:
> 
> outer(x,y,loglik)
> 
> Regards,
> Sundar
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>



More information about the R-help mailing list