#' (Weighted) MLE of Weibull Distribution
#'
#' Two-parameter Weibull distribution is characterized by the following probability density function,
#' \deqn{f(x;\lambda, k)=
#' \frac{k}{\lambda} \left( \frac{x}{\lambda} \right)^{k-1} \exp( -(x/\lambda)^k )
#' }
#' where the domain is \eqn{x \in [0,\infty)} with
#' scale \eqn{\lambda > 0} and shape \eqn{k > 0} parameter.
#'
#' @param x a length-\eqn{n} vector of values in \eqn{[0,\infty)}.
#' @param weight a length-\eqn{n} weight vector. If set as \code{NULL}, it gives an equal weight, leading to standard MLE.
#'
#' @return a named list containing (weighted) MLE of \describe{
#' \item{lambda}{scale parameter \eqn{\lambda}.}
#' \item{k}{shape parameter \eqn{k}.}
#' }
#'
#' @examples
#' # generate data from half-normal
#' x = abs(stats::rnorm(100))
#'
#' # fit unweighted
#' Weibull(x)
#'
#' \dontrun{
#' # put random weights to see effect of weights
#' niter = 500
#' ndata = 200
#'
#' # generate data and fit unweighted MLE
#' x = abs(stats::rnorm(ndata))
#' xmle = Weibull(x)
#'
#' # iterate
#' vec.lbd = rep(0,niter)
#' vec.k = rep(0,niter)
#' for (i in 1:niter){
#' # random weight
#' ww = abs(stats::rnorm(ndata))
#'
#' MLE = Weibull(x, weight=ww)
#' vec.lbd[i] = MLE$lambda
#' vec.k[i] = MLE$k
#' if ((i%%10) == 0){
#' print(paste0(" iteration ",i,"/",niter," complete.."))
#' }
#' }
#'
#' # visualize distributions of weighted estimates and MLE
#' opar <- par(no.readonly=TRUE)
#' par(mfrow=c(1,2))
#' hist(vec.lbd, main="scale 'lambda'")
#' abline(v=xmle$lambda, lwd=3, col="red")
#' hist(vec.k, main="shape 'k'")
#' abline(v=xmle$k, lwd=3, col="blue")
#' par(opar)
#' }
#'
#' @author Kisung You
#' @export
Weibull <- function(x, weight=NULL){
#############################################
# Preprocessing
x = handle_cts_nonneg("Weibull", x)
nx = length(x)
weight = handle_weight("Weibull", weight, nx)
maceps = 10*.Machine$double.eps
#############################################
# Optimize : DEoptim
fopt.Weibull <- function(pars){
# parameters
lambda = pars[1]
k = pars[2]
# log-likelihood
term1 = -((x/lambda)^k)
term2 = (k-1)*(log(x)-log(lambda))
term3 = log(k)-log(lambda)
loglkd = term1+term2+term3
# return
return(-sum(loglkd*weight))
}
sol = DEoptim::DEoptim(fopt.Weibull, lower=c(maceps, maceps), upper=c(1e+5,1e+5),
control=DEoptim::DEoptim.control(trace=FALSE))$optim$bestmem
#############################################
# Return
output = list()
output$lambda = as.double(sol[1])
output$k = as.double(sol[2])
return(output)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.