I want to fit some field data with a custom-made negative exponential probability density function. (Motivation- I eventually want to fit the field data to many of the distributions in table 3 of Bullock Shea and Skarpaas 2006).
First I defined a dnegexp
function according to this post:
Error with custom density function definition for mle2 formula call
dnegexp <- function(x, mya, myb, log=FALSE){
logne <- log(mya)-myb*x
if(log) return(logne) else return(exp(logne))
}
Then I made an rnegexp
function that generates a dataset from this distribution with any given parameters. (Please forgive the inelegance of this function- it is not the topic of this post, but ideas to make it better are welcome...)
rnegexp <- function(n, thisa, thisb){
rnums <- array(data=NA,dim=n)
counter=0
while(counter<=n){
candidate <- runif(1,0,100)
if(runif(1,0,1)<dnegexp(candidate,thisa, thisb)) {
rnums[counter] <- candidate
counter <- counter+1
}
}
return(rnums)
}
With those two functions in hand, I test my workflow by creating a dataset that follows the negative exponential distribution with known parameters:
set.seed(501)
mynegexpvals <- rnegexp(100,0.08, 0.09)
hist(mynegexpvals, freq=FALSE)
mydists <- seq(0,100, by=1)
lines(mydists,dnegexp(mydists, 0.08, 0.09), col="blue", lwd=2)
When I try to use mle2
from the bbmle
package to find the parameters, it gives non-sensical values, even though I gave it the exact generating parameters as starting values:
> library(bbmle)
> mle2(mynegexpvals ~ dnegexp(a,b), start = list(a=0.08, b=0.09), data=data.frame(mynegexpvals))
Call:
mle2(minuslogl = mynegexpvals ~ dnegexp(a, b), start = list(a = 0.08,
b = 0.09), data = data.frame(mynegexpvals))
Coefficients:
a b
2.421577e+12 -6.849330e+12
Log-likelihood: 6.148807e+15
Attempts to bound the search space yields parameter estimates at the boundary:
> mle2(mynegexpvals ~ dnegexp(a,b), start = list(a=0.08, b=0.09), data=data.frame(mynegexpvals), method="L-BFGS-B", lower=c(a=0.04, b=0.0001), upper=c(a=1000, b=1000))
Call:
mle2(minuslogl = mynegexpvals ~ dnegexp(a, b), start = list(a = 0.08,
b = 0.09), method = "L-BFGS-B", data = data.frame(mynegexpvals),
lower = c(a = 0.04, b = 1e-04), upper = c(a = 1000, b = 1000))
Coefficients:
a b
1e+03 1e-04
Log-likelihood: 690.69
Warning message:
In mle2(mynegexpvals ~ dnegexp(a, b), start = list(a = 0.08, b = 0.09), :
some parameters are on the boundary: variance-covariance calculations based on Hessian may be unreliable
Am I missing something major here? Did I define my dnegexp function wrong?