Hans Christensen
Hans Christensen

Reputation: 39

Make likelihood return a vector insted of number, R

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?

Upvotes: 1

Views: 58

Answers (1)

LyzandeR
LyzandeR

Reputation: 37879

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)

Upvotes: 1

Related Questions