1

I want to make my likelihood function return more than one value. I have the following likelihood

loglike <- function(x,mu,tau,u){

logl <- sum(-0.5*log(2*pi) -.5*log(tau^2+u^2) * (1/(2*(tau^2+u^2)))*((x-mu)**2) )

return(-logl)
}

x <- c(3.3569,1.9247,3.6156,1.8446,2.2196,6.8194,2.0820,4.1293,0.3609,2.6197)
u <- c(1,3,0.5,0.2,2,1.7,0.4,1.2,1.1,0.7)  
tau=2

mu <- seq(0,10,length=1000)

I want the likelihood to generate a vector when I plug in the vector of mu, but instead it returns just one number. How can I make the likelihood return the -logl for every mu in a vector?

1 Answers1

1

You could try vapply in order to run the function for each mu:

loglike <- function(x, mu, tau, u){

  logl <- vapply(mu, function(m) {
    logl <- sum(-0.5*log(2*pi) -.5*log(tau^2+u^2) * (1/(2*(tau^2+u^2)))*((x-m)**2) )
  }, FUN.VALUE = numeric(1))

  return(-logl)
}

loglike(x, mu, tau, u)
LyzandeR
  • 37,047
  • 12
  • 77
  • 87
  • This only returns a bunch of NA's. How do you suggest I use this? @LyzandeR – Hans Christensen Jan 08 '18 at 13:55
  • I literally used the values you had in your question. It returns values for me and not NAs. Make sure you run it again from a clean session (i.e. restart R) – LyzandeR Jan 08 '18 at 13:57
  • I want to edit my likelihood function so that when I plug in the mu vector it returns one number for each mu in the likelihood function in a new vector. – Hans Christensen Jan 08 '18 at 14:00
  • Now It seems to work! Thank you! Just one more question regarding my likelihood, do you think it should be return(-logl) or return(logl)? When I plot this I get a local minimum at around mu=2-3, I suppose it should be a maximum (the MLE). – Hans Christensen Jan 08 '18 at 15:25
  • You are welcome :). If you use it for the MLE then maximum would probably make more sense and therefore you could skip the minus sign. – LyzandeR Jan 08 '18 at 15:28
  • I have one more question, although let me know if I should make a new thread on this, but anyways..... The results that I get with this likelihood does not make sense to me. My initial problem was to write a function for the likelihood of $X\sim N(mu,u^2_i+tau^2)$ where u is a known vector and I want to make inference on mu and tau. However, when I run this likelihood in the optim function I get a negative value for tau, which doesnt make sense. How do you propose I change the likelihood? – Hans Christensen Jan 09 '18 at 15:15
  • Please make a new thread if it is a new question. It is always recommended – LyzandeR Jan 09 '18 at 15:16
  • https://stackoverflow.com/questions/48171551/writing-a-proper-normal-log-likelihood-in-r – Hans Christensen Jan 09 '18 at 15:30
  • continuation to my question, see link :) @LyzandeR – Hans Christensen Jan 09 '18 at 15:31
  • do you understand my problem, its essentially being able to do the same with tau for a fixed mu, and then using the optim – Hans Christensen Jan 09 '18 at 16:02