Reputation: 173
I have a function that takes in lambda and a data sample, and finds the corresponding log-likelihood value for each data point:
data <- rpois(n=25, lambda=4)
generateLogLikelihood <- function(lambda, y){
return(dpois(y, lambda, log=TRUE))
}
LogLikelihood = generateLogLikelihood (4,data)
LogLikelihood
I'm asking for a solution to fit this requirement:
I need to use the optimise function to return the value of lambda which maximises the log-likelihood for the given data sample, but I'm getting stuck (this is my first attempt at using optimise). I need to adapt the function to only take 'data' as an input.
Where I'm getting stuck: I'm not sure how/when to apply optimise... given the requirement that my function only takes one input (the data - now called newdata), do I need to optimise outside of the function (but my function requires lambda values), so I'm not sure how to do this.
My current code, which represents 2 separate parts that I don't know how to combine (or may be entirely wrong), is below:
newdata <- c(23,16,18,14,19,20,12,15,15,21)
newlambdas <- seq(min(newdata),max(newdata),0.5)
generateLogLikelihoodNew <- function(y){
return(dpois(y, lambda, log=TRUE))
}
LogLikelihood = optimise(generateLogLikelihoodNew,newdata,lower = min(newlambdas), upper = max(newlambdas), maximum = TRUE)
LogLikelihood
Upvotes: 0
Views: 1085
Reputation: 10385
If you only want to check which of the provided lambda's returns the best fit you can do
generateLogLikelihoodNew <- function(y){
-sum(dpois(newdata, y, log=TRUE))
}
which.min(lapply(newlambdas,generateLogLikelihoodNew))
If however you want to find such value of lambda then you do not need to provide a lambda sequence vector
optimise(
function(x){-sum(dpois(newdata,x,log=TRUE))},
c(0,100)
)
$minimum
[1] 17.3
$objective
[1] 26.53437
Upvotes: 0
Reputation: 270075
There are several problems here:
Thus we have:
LL <- function(lambda, y) sum(dpois(y, lambda, log = TRUE))
optimize(LL, range(newdata), y = newdata, maximum = TRUE)
Upvotes: 1