Search code examples
rmathematical-optimizationnon-linear-regressionmle

Error in using optim to maximise the likelihood in r


So, I have these functions:

funk1 <- function(a,x,l,r) {
x^2*exp(-(l*(1-exp(-r*a))/r))}

funk2 <- function(x,l,r) {
sapply(x, function (s) {
integrate(funk1, lower = 0, upper = s, x=s, l=l, r=r)$value })}  

which are used to explain the data y in,

z <- data.frame(ts = 1:100,
            y = funk2(1:100, l = 1, r = 1) + rpois(100, 1:100))

I wish to use optim to maximise the likelihood, so I defined a likelihood function:

LL_funk <- function(l,r) { 
n=nrow(z)
R = sum((funk2(ts,l,r) - y)^2)
logl = -((n/2)*log(R))
return(-logl)
} 

and I tried to fit using optim

fit <- optim(par=c(0.5,0.5), fn= LL_funk, method="Nelder-Mead")

But I get an error:

 Error in integrate(funk1, lower = 0, upper = s, x = s, l = l, r = r) : 
 a limit is missing 

I am not sure why? I could run nls fitting funk2(x,l,r) to y

nls(y ~ funk2(ts,l,r), data = z, start = list(l = 0.5, r = 0.5))

That means funk2 is working. I guess its the problem with LL function that I have designed, which I cant figure out!! Please Help!


Solution

  • Yup! There were two problems with your function. This worked for me:

    LL_funk <- function(params) { 
      n=nrow(z)
      l = params[1]
      r = params[2]
      R = sum((funk2(z$ts,l,r) - z$y)^2)
      logl = -((n/2)*log(R))
      return(-logl)
    }
    

    Previous issues:

    • LL_funk only takes 1 argument, which is the vector of parameters.
    • In LHS of the assignment of R, ts and y were not actually referring to columns in your dataset.