R/Exponential.R

Defines functions Exponential

Documented in Exponential

#' (Weighted) MLE of Exponential Distribution
#' 
#' Exponential distribution is characterized by the following probability density function,
#' \deqn{f(x;\lambda) = \lambda \exp(-\lambda x)}
#' where the domain is nonnegative real number \eqn{x \in [0,\infty)} with rate parameter \eqn{\lambda > 0}.
#' 
#' @param x a length-\eqn{n} vector of nonnegative real numbers.
#' @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}{rate parameter \eqn{\lambda}.}
#' }
#' 
#' @examples
#' #  generate data from exponential distribution with lambda=1
#' x = stats::rexp(100, rate=1)
#' 
#' #  fit unweighted
#' Exponential(x)
#' 
#' \dontrun{
#' # put random weights to see effect of weights
#' niter = 500
#' ndata = 200
#' 
#' # generate data as above and fit unweighted MLE
#' x    = stats::rexp(ndata, rate=1)
#' xmle = Exponential(x)
#' 
#' # iterate
#' vec.lambda = rep(0,niter)
#' for (i in 1:niter){
#'   # random weight
#'   ww = abs(stats::rnorm(ndata))
#' 
#'   MLE = Exponential(x, weight=ww)
#'   vec.lambda[i] = MLE$lambda
#'   if ((i%%10) == 0){
#'     print(paste0(" iteration ",i,"/",niter," complete.."))
#'   }
#' }
#' 
#' # distribution of weighted estimates + standard MLE
#' opar <- par(no.readonly=TRUE)
#' hist(vec.lambda, main="rate 'lambda'")
#' abline(v=xmle$lambda, lwd=3, col="red")
#' par(opar)
#' } 
#' 
#' @author Kisung You
#' @export
Exponential <- function(x, weight=NULL){
  #############################################
  # Preprocessing
  x = handle_cts_nonneg("Exponential", x)
  nx = length(x)
  weight = handle_weight("Exponential", weight, nx)

  #############################################
  # Optimize : R's optimize
  fopt.Exponential <- function(lambda){
    # log-likelihood
    loglkd = -(lambda*x) + log(lambda) 
    # return
    return(sum(loglkd*weight))
  }
  sol = stats::optimize(fopt.Exponential, lower=maceps, upper=1e+5, maximum = TRUE)
  
  #############################################
  # Return
  output = list()
  output$lambda = as.double(sol$maximum)
  return(output)
}
kyoustat/T4mle documentation built on March 26, 2020, 12:09 a.m.