# Contour plot for a likelihood function

For the likelihood associated with the mixture model

1/4*Normal(mu1,1)+3/4*Normal(mu2,1)

I would like to have a figure as like as following one for a simulated sample of 500 observation from mu1=0 and mu2=2.5. My R code is:

da=rbind(rnorm(10^2),2.5+rnorm(4*10^2))
like=function(mu1,mu2){
sum(log((.25*dnorm(da-mu1)+.75*dnorm(da-mu2))))}
mmu1=seq(-2,5,length.out=length(da))
mmu2=seq(-2,5,length.out=length(da))
post=outer(mmu1,mmu2,like)
image(mmu1,mmu2,post,xlab=expression(mu1),ylab=expression(mu2))


which contains the error:

"Error in dnorm(da-mu1):
dims [product 800] do not match the length of object"


I've changed the length of mmu1 & mmu2, but nothing seemed to be happening. Could someone help me?

The function outer does not work the way you want. When you call outer it passes to the function like the vectors and expects the vector as a result. In your case your function expects the scalars and returns the scalar. Try changing it to something similar to this:

like <- function(mu1,mu2) {
apply(cbind(mu1,mu2),1,function(x)sum(log((.25*dnorm(da-x[1])+.75*dnorm(da-x[2])))))
}


As outer() expects that the function you pass in is vectorized, change your line to

post=outer(mmu1,mmu2,Vectorize(like))


to get