# Weibull样本上的mle2

``````x2<- rweibull(n, shape = 1, scale = 1.5)
library(bbmle)
loglik2 <- function(theta, x){
shape<- theta[1]
scale<- theta[2]
K<- length(theta)
n<- length(x2)
out<- rep(0,K)
for(k in 1:K){
out[k] <- sum(dweibull(x2, shape, scale, log=TRUE))
}
return(out)
}
theta.start<- c(1, 1.4)
(mod <- mle2(loglik2,start=list(theta.start),data=list(x2)))
``````
``````Error in validObject(.Object) :
invalid class “mle2” object: invalid object for slot "fullcoef" in class "mle2": got class "NULL", should be or extend class "numeric"
``````

You can pass the parameters individually rather than as a vector or you can pass a named vector as input instead: see the `vecpar` argument in the docs (and use `parnames(nllfun) <- ...` on your negative log-likelihood function).

``````# some example data
library(bbmle)
set.seed(1)
n = 1000
x2 = rweibull(n, shape = 1, scale = 1.5)
``````

``````loglik2 = function(shape, scale, x)
-sum(dweibull(x, shape=shape, scale=scale, log=TRUE))
``````

``````mle2(loglik2, start=list(shape=1, scale=1),
method="L-BFGS-B",lower=list(shape=0, scale=0),
data=list(x=x2))
#Coefficients:
#   shape    scale
#1.007049 1.485067

# you can also use the formula notation
mle2(x~dweibull(shape=shape, scale=scale),
start=list(shape=1, scale=1),
method="L-BFGS-B",lower=list(shape=0, scale=0),
data=list(x=x2))
``````

Also note in this example that the parameters are forced to be greater than zero by using a log link. From Ben's comment "I would probably recommend a log-link rather than box constraints" -- this is instead of using the `lower` optimisation parameter in the above example.

``````loglik2 = function(theta, x)
-sum(dweibull(x, shape=exp(theta[1]), scale=exp(theta[2]), log=TRUE))

# set the parameter names & set `vecpar` to TRUE
parnames(loglik2) = c("shape", "scale")
m = mle2(loglik2,
start=list(shape=0, scale=0),
data=list(x=x2), vecpar=TRUE)
exp(coef(m)) # exponentiate to get coefficients

# or the function form
mle2(x~dweibull(shape=exp(logshape),scale=exp(logscale)),
start=list(logshape=0, logscale=0),
data=list(x=x2))
``````

A couple of comments on your code; from `?bblme` help page: "Note that the minuslogl function should return the negative log-likelihood" which yours didn't, and the `start` parameters should be a named list.