### Install Development Version of fitdistrplus Source: https://lbbe-software.github.io/fitdistrplus/index.html Install the development version of fitdistrplus from GitHub. Requires the 'remotes' package. ```R if (!requireNamespace("remotes", quietly = TRUE)) install.packages("remotes") remotes::install_github("lbbe-software/fitdistrplus") ``` -------------------------------- ### Example Usage of descdist Source: https://lbbe-software.github.io/fitdistrplus/reference/descdist.html This example demonstrates how to use the `descdist` function with a sample dataset. Setting `set.seed` ensures reproducibility of the random sampling used in the example. ```R set.seed(123) # here just to make random sampling reproducible ``` -------------------------------- ### Fit Poisson Distribution with Quantile Matching Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fit a Poisson distribution to data 'x' using the quantile matching method with a specified starting value for lambda. This example highlights potential sensitivity to the initial guess. ```R fitdist(x, "pois", method="qme", probs=1/2, start=list(lambda=2)) ``` ```text ## Fitting of the distribution ' pois ' by matching quantiles ## Parameters: ## estimate ## lambda 2 ``` -------------------------------- ### Example of prefit with random sampling Source: https://lbbe-software.github.io/fitdistrplus/reference/prefit.html This example demonstrates how to use the prefit function with random sampling for reproducible results. It sets a seed for the random number generator before sampling. ```R set.seed(123) # here just to make random sampling reproducible ``` -------------------------------- ### Using a Custom Optimization Function with fitdist Source: https://lbbe-software.github.io/fitdistrplus/reference/fitdist.html Illustrates how to define and use a custom optimization function ('myoptimize') with fitdist when the default methods are not suitable. This example uses the 'optimize' function internally. ```R mysample <- rexp(100, 5) mystart <- list(rate=8) res1 <- fitdist(mysample, dexp, start= mystart, optim.method="Nelder-Mead") #show the result summary(res1) ``` ```R myoptimize <- function(fn, par, ...) { res <- optimize(f=fn, ..., maximum=FALSE) #assume the optimization function minimize standardres <- c(res, convergence=0, value=res$objective, par=res$minimum, hessian=NA) return(standardres) } #call fitdist with a 'custom' optimization function res2 <- fitdist(mysample, "exp", start=mystart, custom.optim=myoptimize, interval=c(0, 100)) #show the result summary(res2) ``` -------------------------------- ### Fit Geometric Distribution with Different SANN Start Value Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Demonstrates fitting a geometric distribution with the 'SANN' optimization method, using a different starting value for the 'prob' parameter. ```R fitdist(x, "geom", method="qme", probs=1/2, optim.method="SANN", start=list(prob=1/2)) ``` ```text ## Fitting of the distribution ' geom ' by matching quantiles ## Parameters: ## estimate ## prob 0.461 ``` -------------------------------- ### Fit a Pert distribution with fixed min/max and starting mode Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fit a 'pert' distribution to data 'x2' with specified starting values for 'mode' and 'shape', and fixed arguments for 'min' and 'max'. The 'lower' and 'upper' bounds for the distribution parameters are also set. ```R f2 <- fitdist(x2, "pert", start=list(mode=1, shape=1), fix.arg=list(min=min(x2)-eps, max=max(x2)+eps), lower=c(min(x2), 0), upper=c(max(x2), Inf)) ``` -------------------------------- ### Fit distribution with 1000 variates Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Demonstrates fitting a distribution with a larger sample size to observe parameter convergence. This example shows the results of a 3-parameter fit compared to a 2-parameter fit and the true values. ```r ## shape 12.0355 10.6653 11 ## rate 3.1299 2.9059 3 ## low 5.0008 5.0000 5 ## mean sq. error 0.3631 0.0403 0 ## rel. error 0.0459 0.0206 0 ``` -------------------------------- ### Load fitdistrplus Package Source: https://lbbe-software.github.io/fitdistrplus/index.html Load the fitdistrplus package into your current R session after installation. ```R require("fitdistrplus") ``` -------------------------------- ### prefit Source: https://lbbe-software.github.io/fitdistrplus/reference/prefit.html Searches for good starting values for the parameters of a probability distribution. This is often a preliminary step before a more rigorous fitting procedure. ```APIDOC ## Function: prefit ### Description Searches for good starting values for the parameters of a probability distribution. This is often a preliminary step before a more rigorous fitting procedure. ### Usage ``` prefit(data, distr, method = c("mle", "mme", "qme", "mge"), feasible.par, memp=NULL, order=NULL, probs=NULL, qtype=7, gof=NULL, fix.arg=NULL, lower, upper, weights=NULL, silent=TRUE, ...) ``` ### Arguments * **data** (numeric vector) - The input data for fitting. * **distr** (character string or function) - The name of the distribution or its density function. * **method** (character string) - The fitting method to use: 'mle' (maximum likelihood estimation), 'mme' (moment matching estimation), 'qme' (quantile matching estimation), or 'mge' (maximum goodness-of-fit estimation). * **feasible.par** (named list or function) - Initial values for parameters or a function to compute them. * **memp** (function) - A function implementing empirical moments. * **order** (numeric vector) - The order(s) of the moments to be used. * **probs** (numeric vector) - Probabilities for quantile matching. * **qtype** (numeric) - The quantile type used by the R `quantile` function (default is 7). * **gof** (character string) - The goodness-of-fit distance measure (e.g., "CvM", "KS", "AD"). * **fix.arg** (named list or function) - Fixed parameter values or a function to compute them. * **lower** (numeric) - Lower bounds for the parameters. * **upper** (numeric) - Upper bounds for the parameters. * **weights** (numeric vector) - Optional weights for the fitting process. * **silent** (logical) - If TRUE, suppresses warnings. * **...** - Further arguments passed to underlying estimation functions. ### Details This function transforms parameters to ensure they lie within their valid ranges (e.g., using logarithm for positive parameters, logit for probabilities) before performing optimization using a quasi-Newton algorithm. The parameters are then transformed back to their original scale. ### Value A named list containing the estimated parameters and other relevant information. ### See Also `mledist`, `mmedist`, `qmedist`, `mgedist`, `fitdist` ### References Delignette-Muller ML and Dutang C (2015), "fitdistrplus: An R Package for Fitting Distributions". Journal of Statistical Software, 64(4), 1-34. ### Author Christophe Dutang and Marie-Laure Delignette-Muller. ### Examples ```R set.seed(123) # for reproducibility # Example usage would typically follow here, demonstrating how to call prefit # with sample data and distribution choices. ``` ``` -------------------------------- ### Fit 'tiexp' distribution with MLE Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fits the 'tiexp' distribution to data 'x' using maximum likelihood estimation. It demonstrates how to specify starting values and fix certain arguments. ```R f2 <- fitdist(x, "tiexp", method="mle", start=list(rate=3), fix.arg=list(low=min(x), upp=max(x))) (f2 <- fitdist(x, "tiexp", method="mle", start=list(rate=3), fix.arg=list(low=min(x), upp=max(x)))) ``` -------------------------------- ### Fit Geometric Distribution with Quantile Matching Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fit a geometric distribution to data 'x' using the quantile matching method. This example shows the default optimization method and its output. ```R fitdist(x, "geom", method="qme", probs=1/2, start=list(prob=1/20), control=list(trace=1, REPORT=1)) ``` ```text ## Fitting of the distribution ' geom ' by matching quantiles ## Parameters: ## estimate ## prob 0.05 ``` -------------------------------- ### Install Stable Version of fitdistrplus Source: https://lbbe-software.github.io/fitdistrplus/index.html Use this command to install the stable version of the fitdistrplus package from CRAN. ```R install.packages("fitdistrplus") ``` -------------------------------- ### Fit Poisson Distribution with SANN Optimization Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fit a Poisson distribution using the quantile matching method and the 'SANN' optimization algorithm, with a specified starting value for lambda. ```R fitdist(x, "pois", method="qme", probs=1/2, optim.method="SANN", start=list(lambda=2)) ``` -------------------------------- ### Fit Burr Distribution with Default Nelder-Mead Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Demonstrates fitting a Burr distribution to data using the default Nelder-Mead optimization algorithm. This example may encounter an iteration limit error. ```R data("danishuni") try(fitdist(danishuni$Loss, "burr")) ``` -------------------------------- ### QQ Plot Comparison with ggplot2 Style Source: https://lbbe-software.github.io/fitdistrplus/reference/graphcompcens.html Creates QQ plot comparisons using the `ggplot2` plotting system. This requires the `ggplot2` package to be installed and loaded. ```r if (requireNamespace ("ggplot2", quietly = TRUE)) { qqcompcens(list(fitsfn,fitsfl,fitsfg), ynoise = FALSE, plotstyle = "ggplot") } ``` -------------------------------- ### Customizing Graphical Output with ggplot2 Source: https://lbbe-software.github.io/fitdistrplus/reference/graphcomp.html Demonstrates customizing graphical output using `plotstyle = "ggplot"` for density, CDF, QQ, and PP plots. Requires the ggplot2 package to be installed. ```R data(groundbeef) serving <- groundbeef$serving fitW <- fitdist(serving, "weibull") fitln <- fitdist(serving, "lnorm") fitg <- fitdist(serving, "gamma") if (requireNamespace ("ggplot2", quietly = TRUE)) { denscomp(list(fitW, fitln, fitg), plotstyle = "ggplot") cdfcomp(list(fitW, fitln, fitg), plotstyle = "ggplot") qqcomp(list(fitW, fitln, fitg), plotstyle = "ggplot") ppcomp(list(fitW, fitln, fitg), plotstyle = "ggplot") } ``` -------------------------------- ### Fit Beta Distribution using MLE with Gradient Source: https://lbbe-software.github.io/fitdistrplus/articles/Optimalgo.html Fits a beta distribution to the data 'x' using the Maximum Likelihood Estimation (MLE) method. This example utilizes the 'fitbench' function, specifying the distribution as 'beta', method as 'mle', and providing the gradient function 'grlnlbeta'. ```R unconstropt <- fitbench(x, "beta", "mle", grad=grlnlbeta, lower=0) ``` -------------------------------- ### Plotting confidence intervals on quantiles with custom points Source: https://lbbe-software.github.io/fitdistrplus/reference/CIcdfplot.html This example shows how to plot confidence intervals on quantiles derived from bootstrap estimates. It includes options for specifying the output format, fill and line colors, x-axis limits, and associating names with specific points. ```APIDOC ## CIcdfplot with bootstrap quantiles and custom points ### Description Plots confidence intervals on quantiles derived from bootstrap estimates, with options for custom point labeling and axis limits. ### Parameters - **bln**: A bootdist object containing bootstrap estimates. - **CI.output**: Specifies the output type for confidence intervals. "quantile" for quantiles. - **CI.fill**: The fill color for the confidence interval band. - **CI.col**: The color of the confidence interval band outline. - **xlim**: The limits for the x-axis. - **name.points**: A vector of names to label specific points on the plot. - **plotstyle**: Optional. If set to "ggplot", uses ggplot2 for plotting. ``` -------------------------------- ### Fit U-shaped Beta Distribution with Custom Method Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fits a U-shaped beta distribution using the Nelder-Mead optimization method. Requires specifying starting values and lower bounds for parameters. ```R x <- rbeta(1000, 0.5, 0.5) fitdist(x, "beta2", start=list(shape=0.4), optim.method="Nelder-Mead", lower=1e-1) ``` -------------------------------- ### Fit a Normal Distribution and Get Goodness-of-Fit Statistics Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html This snippet demonstrates fitting a normal distribution to a small sample of Poisson-generated data and then calculating goodness-of-fit statistics. It is useful for assessing the fit of a normal distribution when parameters are estimated from the data. ```r x4 <- rpois(n = 50, lambda = 1) f4 <- fitdist(x4, "norm") g4 <- gofstat(f4) g4$kstest ``` -------------------------------- ### Bootstrap Replicates with Optimalgo Source: https://lbbe-software.github.io/fitdistrplus/articles/Optimalgo.html Simulates bootstrap replicates using the 'bootdist' function for a fitted distribution. Specifies the number of iterations, parallel processing, and number of CPUs. The 'summary' function displays results, and 'plot' visualizes them against true values. ```R b1 <- bootdist(fitdist(x, "nbinom", method = "mle", optim.method = "BFGS"), niter = 100, parallel = "snow", ncpus = 2) summary(b1) ``` ```R plot(b1, trueval=trueval[c("size", "mu")]) ``` -------------------------------- ### Fit Gamma Distribution with Maximum Likelihood Source: https://lbbe-software.github.io/fitdistrplus/reference/fitdist.html Demonstrates fitting a gamma distribution to the 'serving' dataset using maximum likelihood estimation and displays a summary of the fit. ```R fit1 <- fitdist(serving, "gamma") summary(fit1) ``` -------------------------------- ### summary.bootdist Source: https://lbbe-software.github.io/fitdistrplus/reference/bootdist.html Provides a summary of the bootstrap simulation results, including statistics for the distribution parameters. ```APIDOC ## Method: summary.bootdist ### Description Summarizes an object of class 'bootdist'. ### Usage ```R summary(object, ...) ``` ### Arguments * **object** (bootdist object) - An object of class "bootdist". * **...** - Further arguments to be passed to generic methods. ``` -------------------------------- ### Fit Gamma Distribution with Custom Genetic Algorithm Optimization Source: https://lbbe-software.github.io/fitdistrplus/reference/fitdist.html Illustrates fitting a gamma distribution using a custom optimization function based on the genetic algorithm from the 'rgenoud' package. This approach is useful for complex or non-convex optimization landscapes. ```R mygenoud <- function(fn, par, ...) { require("rgenoud") res <- genoud(fn, starting.values=par, ...) standardres <- c(res, convergence=0) return(standardres) } fit2 <- fitdist(serving, "gamma", custom.optim=mygenoud, nvars=2, Domains=cbind(c(0, 0), c(10, 10)), boundary.enforcement=1, print.level=1, hessian=TRUE) summary(fit2) ``` -------------------------------- ### Attempt to Fit Gumbel Distribution to Censored Data Source: https://lbbe-software.github.io/fitdistrplus/reference/graphcompcens.html Demonstrates an attempt to fit a Gumbel distribution to censored data. This snippet highlights a potential error related to specifying starting parameters for the Gumbel distribution, indicating that 'start' must specify names which are arguments to the distribution function. ```R dgumbel <- function(x,a,b) 1/b*exp((a-x)/b)*exp(-exp((a-x)/b)) pgumbel <- function(q,a,b) exp(-exp((a-q)/b)) qgumbel <- function(p,a,b) a-b*log(-log(p)) fitsfg<-fitdistcens(Clog10,"gumbel",start=list(a=-3,b=3)) summary(fitsfg) ``` -------------------------------- ### Usage of the prefit function Source: https://lbbe-software.github.io/fitdistrplus/reference/prefit.html Demonstrates the basic syntax and arguments for the prefit function, including data, distribution, and fitting method. ```R prefit(data, distr, method = c("mle", "mme", "qme", "mge"), feasible.par, memp=NULL, order=NULL, probs=NULL, qtype=7, gof=NULL, fix.arg=NULL, lower, upper, weights=NULL, silent=TRUE, ...) ``` -------------------------------- ### Fit Log-Logistic Distribution Source: https://lbbe-software.github.io/fitdistrplus/reference/fitdist.html Fits a log-logistic distribution to a dataset using predefined starting values. Requires the 'actuar' package. ```R require("actuar") x <- c(2.3,0.1,2.7,2.2,0.4,2.6,0.2,1.,7.3,3.2,0.8,1.2,33.7,14., 21.4,7.7,1.,1.9,0.7,12.6,3.2,7.3,4.9,4000.,2.5,6.7,3.,63., 6.,1.6,10.1,1.2,1.5,1.2,30.,3.2,3.5,1.2,0.2,1.9,0.7,17., 2.8,4.8,1.3,3.7,0.2,1.8,2.6,5.9,2.6,6.3,1.4,0.8) #log logistic ft_llogis <- fitdist(x,'llogis') ``` -------------------------------- ### Parallel Bootstrapping with multicore Source: https://lbbe-software.github.io/fitdistrplus/reference/bootdist.html Performs parametric bootstrapping using the 'multicore' parallel backend. Ensure you are not on Windows for this option. The code measures the execution time. ```R ptm <- proc.time() summary(bootdist(f1, niter = niter, parallel = "multicore", ncpus = 2)) #> Parametric bootstrap medians and 95% percentile CI #> Median 2.5% 97.5% #> shape 4.02586191 3.45250533 4.7634281 #> rate 0.05466294 0.04663766 0.0655417 proc.time() - ptm #> user system elapsed #> 4.386 0.431 2.431 ``` -------------------------------- ### Fit Inverse Weibull Distribution Source: https://lbbe-software.github.io/fitdistrplus/reference/fitdist.html Fits an inverse Weibull distribution to a dataset using predefined starting values. Requires the 'actuar' package. ```R x <- c(0.3837053, 0.8576858, 0.3552237, 0.6226119, 0.4783756, 0.3139799, 0.4051403, 0.4537631, 0.4711057, 0.5647414, 0.6479617, 0.7134207, 0.5259464, 0.5949068, 0.3509200, 0.3783077, 0.5226465, 1.0241043, 0.4384580, 1.3341520) #inverse weibull ft_iw <- fitdist(x,'invweibull') ``` -------------------------------- ### Fit Gumbel Distribution to Data Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fits the Gumbel distribution to the 'serving' variable in the 'groundbeef' dataset using specified starting values for parameters 'a' and 'b'. ```R data(groundbeef) fitgumbel <- fitdist(groundbeef$serving, "gumbel", start=list(a=10, b=10)) ``` -------------------------------- ### mgedist Function Signature Source: https://lbbe-software.github.io/fitdistrplus/reference/mgedist.html Defines the usage of the mgedist function, outlining its parameters for data, distribution, goodness-of-fit criteria, starting values, and optimization methods. ```R mgedist(data, distr, gof = "CvM", start = NULL, fix.arg = NULL, optim.method = "default", lower = -Inf, upper = Inf, custom.optim = NULL, silent = TRUE, gradient = NULL, checkstartfix=FALSE, calcvcov=FALSE, ...) ``` -------------------------------- ### print.bootdist Source: https://lbbe-software.github.io/fitdistrplus/reference/bootdist.html Prints the results of a bootstrap simulation for fitted distribution parameters. ```APIDOC ## Method: print.bootdist ### Description Prints an object of class 'bootdist'. ### Usage ```R print(x, ...) ``` ### Arguments * **x** (bootdist object) - An object of class "bootdist". * **...** - Further arguments to be passed to generic methods. ``` -------------------------------- ### Custom Optimization with Genetic Algorithm Source: https://lbbe-software.github.io/fitdistrplus/reference/fitdistcens.html This snippet shows how to define and use a custom optimization function, specifically the genetic algorithm from the rgenoud package, with fitdistcens. It requires loading the rgenoud package and defining a wrapper function for genoud. ```R mygenoud <- function(fn, par, ...) { require("rgenoud") res <- genoud(fn, starting.values=par, ...) standardres <- c(res, convergence=0) return(standardres) } # call fitdistcens with a 'custom' optimization function fit.with.genoud <- fitdistcens(log10EC50,"logis", custom.optim=mygenoud, nvars=2, Domains=cbind(c(0,0), c(5, 5)), boundary.enforcement=1, print.level=1, hessian=TRUE) ``` -------------------------------- ### Summary Output for Lognormal Fit Source: https://lbbe-software.github.io/fitdistrplus/articles/fitdistrplus_vignette.html Example output showing the results of fitting a lognormal distribution to censored data, including parameter estimates and goodness-of-fit statistics. ```R ## Fitting of the distribution ' lnorm ' By maximum likelihood on censored data ## Parameters ## estimate Std. Error ## meanlog 3.3854 0.06487 ## sdlog 0.4961 0.05455 ## Loglikelihood: -139.1 AIC: 282.1 BIC: 287.5 ## Correlation matrix: ## meanlog sdlog ## meanlog 1.0000 0.2938 ## sdlog 0.2938 1.0000 ``` -------------------------------- ### Compare Parameter Estimates from Different Optimizers Source: https://lbbe-software.github.io/fitdistrplus/articles/fitdistrplus_vignette.html This snippet compares the estimated parameters (shape α and rate λ for gamma distribution) obtained from different optimization algorithms, including the custom `fgenoud` optimizer, the default `NM` (Nelder-Mead), `BFGS`, `SANN`, and `CG`. ```R cbind(NM = fNM$estimate, BFGS = fBFGS$estimate, SANN = fSANN$estimate, CG = fCG$estimate, fgenoud = fgenoud$estimate) ``` -------------------------------- ### Plotting Fitted Distribution with Confidence Intervals Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Plots the fitted distribution, similar to the first example, but specifically for a fitted gamma distribution object. Use for visualizing the fit and its uncertainty. ```R par(mfrow=c(1,1), mar=c(4,4,2,1)) llplot(fg, back.col = FALSE, fit.show=TRUE) ``` -------------------------------- ### Bootstrap Parameter Estimation and Summary Source: https://lbbe-software.github.io/fitdistrplus/articles/fitdistrplus_vignette.html Use `bootdist` to perform a parametric bootstrap for non-censored data and `summary` to view the bootstrapped medians and confidence intervals. The number of iterations for which the estimation converged is also reported. ```R bendo.B <- bootdist(fendo.B, niter = 1001) summary(bendo.B) ``` -------------------------------- ### Calculate Wald confidence intervals Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html This example demonstrates the calculation of Wald confidence intervals for parameter estimates. It uses the estimated parameters and their standard errors to compute the interval bounds. ```r fn$estimate + cbind("estimate"= 0, "2.5%"= -1.96*fn$sd, "97.5%"= 1.96*fn$sd) ``` -------------------------------- ### print.density.bootdist Source: https://lbbe-software.github.io/fitdistrplus/reference/bootdist.html Prints the density object for bootstrapped parameter values. ```APIDOC ## Method: print.density.bootdist ### Description Prints an object of class 'density.bootdist'. ### Usage ```R print(x, ...) ``` ### Arguments * **x** (density.bootdist object) - An object of class "density.bootdist". * **...** - Further arguments to be passed to generic methods. ``` -------------------------------- ### Fit Truncated Inflated Exponential Distribution (MLE) Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fits a truncated inflated exponential distribution using MLE. This example shows fitting when the bounds are unknown and need to be estimated. ```R (f1 <- fitdist(x, "tiexp", method="mle", start=list(rate=3, low=0, upp=20))) ``` -------------------------------- ### CDF Comparison with ggplot2 Integration Source: https://lbbe-software.github.io/fitdistrplus/reference/graphcompcens.html Generates a CDF comparison plot using ggplot2 style. This requires the ggplot2 package to be installed and loaded. The output can be further customized with ggplot2 themes. ```R if (requireNamespace ("ggplot2", quietly = TRUE)) { cdfcompcens <- cdfcompcens(list(fitsfn,fitsfl,fitsfg),datacol="orange",fillrect = NA, legendtext=c("normal","logistic","Gumbel"), xlab="bacterial concentration (CFU/g)",ylab="F", xlegend = "bottom",lines01 = TRUE, plotstyle = "ggplot") cdfcompcens + ggplot2::theme_minimal() + ggplot2::ggtitle("Bacterial contamination fits") } ``` -------------------------------- ### Describe Sample from Beta Distribution with Custom Colors Source: https://lbbe-software.github.io/fitdistrplus/reference/descdist.html Describes a sample from a beta distribution, estimating uncertainty via bootstrapping. Allows customization of observed point and bootstrap colors and plotting characters. ```r descdist(rbeta(100,shape1=0.05,shape2=1),boot=11, obs.col="blue", obs.pch = 15, boot.col="darkgreen") ``` -------------------------------- ### Calculating Quantiles for Geometric Distribution Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Shows how to calculate quantiles for a geometric distribution using the qgeom function. This is useful for finding values corresponding to given probabilities. ```R qgeom(c(0.3, 0.6, 0.9), prob=1/2) ``` -------------------------------- ### PP Plots with ggplot2 Source: https://lbbe-software.github.io/fitdistrplus/reference/graphcompcens.html Generates PP plots using ggplot2 style for a list of fitted distributions. This requires the ggplot2 package. The first example shows default ggplot styling. ```R if (requireNamespace ("ggplot2", quietly = TRUE)) { ppcompcens(list(fitsfn,fitsfl,fitsfg), plotstyle = "ggplot") } ``` -------------------------------- ### Compare Computation Time of Optimization Methods Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Compares the computation time of the Nelder-Mead algorithm versus the L-BFGS-B algorithm for fitting a Burr distribution. Use this to understand performance differences between optimization methods. ```R print(prod(coef(fitBurr_cvg2)[1:2]), digits=5) ``` ```R system.time(fitdist(danishuni$Loss, "burr", upper=100)) ``` ```R system.time(fitdist(danishuni$Loss, "burr", lower=.Machine$double.eps, optim.method="L-BFGS-B")) ``` -------------------------------- ### print.density.bootdistcens Source: https://lbbe-software.github.io/fitdistrplus/reference/bootdistcens.html Prints a kernel density estimate for a bootstrap object. ```APIDOC ## print.density.bootdistcens ### Description Prints an object of class 'density.bootdistcens'. ### Usage ```R print(x, ...) ``` ### Arguments * **x** (density.bootdistcens object) - An object of class 'density.bootdistcens'. * **...** - Further arguments to be passed to generic methods. ``` -------------------------------- ### Fit Zero-Modified Geometric Distribution Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Generates random data from a zero-modified geometric distribution and then fits this distribution to the generated data using specified starting values for parameters 'p1' and 'p2'. ```R x2 <- rzmgeom(1000, 1/2, 1/10) fitdist(x2, "zmgeom", start=list(p1=1/2, p2=1/2)) ``` -------------------------------- ### Fit Gamma and Lognormal Distributions and Compare Goodness-of-Fit Source: https://lbbe-software.github.io/fitdistrplus/reference/gofstat.html This snippet demonstrates fitting both gamma and log-normal distributions to the 'serving' data using maximum likelihood estimation. It then calculates and displays goodness-of-fit statistics and criteria for each individual fit, followed by a comparison of these statistics when both fits are provided to gofstat. ```R set.seed(123) # here just to make random sampling reproducible # (1) fit of two distributions to the serving size data # by maximum likelihood estimation # data(groundbeef) serving <- groundbeef$serving (fitg <- fitdist(serving, "gamma")) #> Fitting of the distribution ' gamma ' by maximum likelihood #> Parameters: #> estimate Std. Error #> shape 4.00955898 0.341451640 #> rate 0.05443907 0.004937239 gofstat(fitg) #> Goodness-of-fit statistics #> 1-mle-gamma #> Kolmogorov-Smirnov statistic 0.1281486 #> Cramer-von Mises statistic 0.6936274 #> Anderson-Darling statistic 3.5672625 #> #> Goodness-of-fit criteria #> 1-mle-gamma #> Akaike's Information Criterion 2511.250 #> Bayesian Information Criterion 2518.325 (fitln <- fitdist(serving, "lnorm")) #> Fitting of the distribution ' lnorm ' by maximum likelihood #> Parameters: #> estimate Std. Error #> meanlog 4.1693701 0.03366988 #> sdlog 0.5366095 0.02380783 gofstat(fitln) #> Goodness-of-fit statistics #> 1-mle-lnorm #> Kolmogorov-Smirnov statistic 0.1493090 #> Cramer-von Mises statistic 0.8277358 #> Anderson-Darling statistic 4.5436542 #> #> Goodness-of-fit criteria #> 1-mle-lnorm #> Akaike's Information Criterion 2526.639 #> Bayesian Information Criterion 2533.713 gofstat(list(fitg, fitln)) #> Goodness-of-fit statistics #> 1-mle-gamma 2-mle-lnorm #> Kolmogorov-Smirnov statistic 0.1281486 0.1493090 #> Cramer-von Mises statistic 0.6936274 0.8277358 #> Anderson-Darling statistic 3.5672625 4.5436542 #> #> Goodness-of-fit criteria #> 1-mle-gamma 2-mle-lnorm #> Akaike's Information Criterion 2511.250 2526.639 #> Bayesian Information Criterion 2518.325 2533.713 ``` -------------------------------- ### Fit Triangular Distribution using Kolmogorov-Smirnov Source: https://lbbe-software.github.io/fitdistrplus/reference/mgedist.html Fits a triangular distribution to a sample of 100 values using the Kolmogorov-Smirnov distance. Requires the 'mc2d' package and provides starting values for parameters. ```R require("mc2d") t <- rtriang(100,min=5,mode=6,max=10) mgedist(t,"triang",start = list(min=4, mode=6,max=9),gof="KS") ``` -------------------------------- ### Fit Geometric Distribution using Quantile Matching Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fits a geometric distribution to sample data 'x' using the 'qme' (quantile matching estimation) method. Demonstrates the sensitivity to initial values in deterministic optimization. ```R fitdist(x, "geom", method="qme", probs=1/2, start=list(prob=1/2), control=list(trace=1, REPORT=1)) ``` -------------------------------- ### quantile.bootdist Source: https://lbbe-software.github.io/fitdistrplus/reference/quantile.html Calculates quantiles and confidence intervals from a bootstrapped distribution object. ```APIDOC ## quantile.bootdist ### Description Calculates quantiles and confidence intervals from a bootstrapped distribution object. ### Usage ```R quantile(x, probs = seq(0.1, 0.9, by=0.1), CI.type = "two.sided", CI.level = 0.95, ...) ``` ### Arguments * `x` (bootdist): An object of class "bootdist". * `probs` (numeric vector): Probabilities in [0, 1] for which quantiles are calculated. * `CI.type` (character): Type of confidence intervals: "two.sided", "less", or "greater". * `CI.level` (numeric): The confidence level (default is 0.95). * `...`: Further arguments. ### Value A list containing: * `quantiles` (dataframe): Estimated quantiles for each probability. * `probs` (numeric vector): The probabilities used. * `bootquant` (dataframe): Bootstrap values for each quantile. * `quantCI` (dataframe): Confidence intervals for each quantile. * `quantmedian` (numeric vector): Median bootstrap estimates. * `CI.type` (character): Type of confidence interval used. * `CI.level` (numeric): Confidence level used. * `nbboot` (integer): Number of bootstrap samples. * `nbconverg` (integer): Number of iterations where optimization converged. ### See also `bootdist`, `bootdistcens` ``` -------------------------------- ### Fit Geometric Distribution with SANN Optimization Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fit a geometric distribution using the quantile matching method, but specifying the 'SANN' optimization method for potentially better results with difficult starting values. ```R fitdist(x, "geom", method="qme", probs=1/2, optim.method="SANN", start=list(prob=1/20)) ``` ```text ## Fitting of the distribution ' geom ' by matching quantiles ## Parameters: ## estimate ## prob 0.415 ``` -------------------------------- ### Fit Burr Distribution with Initial Values Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fits the Burr distribution to the 'ATV' variable in the 'endosulfan' dataset using specified starting values for shape and rate parameters. Requires the 'actuar' package. ```R data("endosulfan") require("actuar") fendo.B <- fitdist(endosulfan$ATV, "burr", start = list(shape1 = 0.3, shape2 = 1, rate = 1)) ``` -------------------------------- ### print.bootdistcens Source: https://lbbe-software.github.io/fitdistrplus/reference/bootdistcens.html Prints the results of a bootstrap simulation for censored data. ```APIDOC ## print.bootdistcens ### Description Prints an object of class 'bootdistcens'. ### Usage ```R print(x, ...) ``` ### Arguments * **x** (bootdistcens object) - An object of class "bootdistcens". * **...** - Further arguments to be passed to generic methods. ``` -------------------------------- ### Basic Usage of Surv2fitdistcens with Interval Censoring Source: https://lbbe-software.github.io/fitdistrplus/reference/Surv2fitdistcens.html Demonstrates the basic usage of Surv2fitdistcens with interval censored data. Ensure your data is prepared with 'time' and 'time2' columns representing the interval start and end. ```R Surv2fitdistcens(time = origdata$followuptime, time2 = origdata$followuptime, event = origdata$Death, type = "interval") ``` -------------------------------- ### Fit Lognormal Distribution using Method of Moments Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fit a log-normal distribution using the method of moments (mme) with a specified number of bootstrap values. This example demonstrates fitting with 100 bootstrap values. ```R f.ln.MME <- fitdist(rlnorm(1000), "lnorm", method = "mme", order = 1:2) ``` -------------------------------- ### summary.bootdistcens Source: https://lbbe-software.github.io/fitdistrplus/reference/bootdistcens.html Summarizes the results of a bootstrap simulation for censored data. ```APIDOC ## summary.bootdistcens ### Description Summarizes an object of class 'bootdistcens'. ### Usage ```R summary(object, ...) ``` ### Arguments * **object** (bootdistcens object) - An object of class "bootdistcens". * **...** - Further arguments to be passed to generic methods. ``` -------------------------------- ### Log-Likelihood Plot for Censored Data Source: https://lbbe-software.github.io/fitdistrplus/reference/logLik-plot.html Visualizes the log-likelihood for a distribution fitted to censored data. This example uses the 'lnorm' distribution and shows how to display the maximum likelihood estimate and toggle between log-likelihood and likelihood plots. ```R # (5) a distribution with two parameters fitted on censored data # data(salinity) fsal <- fitdistcens(salinity, "lnorm") llplot(fsal, fit.show = TRUE) llplot(fsal, fit.show = TRUE, loglik = FALSE) ``` -------------------------------- ### Fit Gamma Distribution with Custom genoud Optimizer Source: https://lbbe-software.github.io/fitdistrplus/articles/fitdistrplus_vignette.html This code fits a gamma distribution to the `groundbeef$serving` data using the custom `mygenoud` optimizer. It demonstrates passing various arguments from `fitdist` to `genoud` and setting `hessian = TRUE`. ```R fgenoud <- mledist(groundbeef$serving, "gamma", custom.optim = mygenoud, nvars = 2, max.generations = 10, Domains = cbind(c(0, 0), c(10, 10)), boundary.enforcement = 1, hessian = TRUE, print.level = 0, P9 = 10) ``` -------------------------------- ### Fit Triangular Distribution using Cramer-von Mises Source: https://lbbe-software.github.io/fitdistrplus/reference/mgedist.html Fits a triangular distribution to a sample of 100 values using the Cramer-von Mises distance. Requires the 'mc2d' package and provides starting values for parameters. ```R require("mc2d") t <- rtriang(100,min=5,mode=6,max=10) mgedist(t,"triang",start = list(min=4, mode=6,max=9),gof="CvM") ``` -------------------------------- ### Summarize Bootdistcens Object Source: https://lbbe-software.github.io/fitdistrplus/reference/bootdistcens.html Provides a summary of the bootstrap simulation results for censored data. This includes key statistics of the bootstrap parameter estimates. ```R summary(object, ...) ``` -------------------------------- ### Compare Sequential and Parallel Bootstrap Performance Source: https://lbbe-software.github.io/fitdistrplus/reference/bootdist.html Compare the execution time of sequential and parallel (using 'snow') versions of the bootstrap function. This helps in choosing the most efficient method for a given number of iterations and computational resources. ```R niter <- 1001 data(groundbeef) x1 <- groundbeef$serving f1 <- fitdist(x1, "gamma") # sequential version ptm <- proc.time() summary(bootdist(f1, niter = niter)) proc.time() - ptm ``` ```R require("parallel") ptm <- proc.time() summary(bootdist(f1, niter = niter, parallel = "snow", ncpus = 2)) proc.time() - ptm ``` -------------------------------- ### Fit Gumbel Distribution to Censored Data Source: https://lbbe-software.github.io/fitdistrplus/reference/fitdistcens.html Attempts to fit a Gumbel distribution to censored data (log10EC50). This snippet demonstrates the initial call and highlights a potential error if 'start' parameters are not correctly specified. ```R fg <- fitdistcens(log10EC50,"gumbel",start=list(a=1,b=1)) ``` -------------------------------- ### mledist function signature Source: https://lbbe-software.github.io/fitdistrplus/reference/mledist.html This is the main function signature for fitting distributions using maximum likelihood. It accepts data, distribution name, starting values, fixed parameters, optimization method, bounds, and other optional arguments. ```R mledist(data, distr, start = NULL, fix.arg = NULL, optim.method = "default", lower = -Inf, upper = Inf, custom.optim = NULL, weights = NULL, silent = TRUE, gradient = NULL, checkstartfix=FALSE, calcvcov=FALSE, ...) ``` -------------------------------- ### Loading the 'actuar' Package Source: https://lbbe-software.github.io/fitdistrplus/articles/fitdistrplus_vignette.html Loads the 'actuar' package, which provides additional distributions like Pareto and Burr, often used in ecotoxicology. This is a prerequisite for fitting these distributions using fitdistrplus. ```R require("actuar") ``` -------------------------------- ### Compute Confidence Intervals on Functions of Parameters Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Calculate confidence intervals for functions of fitted distribution parameters using bootstrap samples. This example computes a 95% confidence interval for the Potentially Affected Portion (PAF) at a given exposure. ```R exposure <- 1.2 # Bootstrap sample of the PAF at this exposure PAF <- pnorm(exposure, mean = bootsample$estim$mean, sd = bootsample$estim$sd) # confidence interval from 2.5 and 97.5 percentiles quantile(PAF, probs = c(0.025, 0.975)) ``` -------------------------------- ### Compare CDFs of 'tiexp' fits Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Compares the cumulative distribution functions (CDFs) of two 'tiexp' distribution fits (f1 and f2) against the empirical CDF and a true CDF. This visualization aids in assessing the fit. ```R par(mfrow=c(1,1), mar=c(4,4,2,1)) cdfcomp(list(f1, f2), do.points = FALSE, addlegend=FALSE, xlim=c(0, 3.5)) curve(ptiexp(x, 1, .5, 3), add=TRUE, col="blue", lty=3) legend("bottomright", lty=1:3, col=c("red", "green", "blue", "black"), legend=c("full MLE", "MLE fixed arg", "true CDF", "emp. CDF")) ``` -------------------------------- ### Fit Gumbel Distribution to Censored Data Source: https://lbbe-software.github.io/fitdistrplus/reference/mledist.html Demonstrates fitting a Gumbel distribution to censored data. Requires defining the distribution's PDF, CDF, and quantile functions. Note the error indicating incorrect parameter specification in 'start'. ```R data(fluazinam) log10EC50 <-log10(fluazinam) # definition of the Gumbel distribution dgumbel <- function(x,a,b) 1/b*exp((a-x)/b)*exp(-exp((a-x)/b)) pgumbel <- function(q,a,b) exp(-exp((a-q)/b)) qgumbel <- function(p,a,b) a-b*log(-log(p)) mledist(log10EC50,"gumbel",start=list(a=0,b=2),optim.method="Nelder-Mead") #> Error in checkparamlist(arg_startfix$start.arg, arg_startfix$fix.arg, argddistname, hasnodefaultval): 'start' must specify names which are arguments to 'distr'. ``` -------------------------------- ### Describe Serving Size Data Source: https://lbbe-software.github.io/fitdistrplus/reference/descdist.html Describes the serving size data from the groundbeef dataset. Uncertainty for skewness and kurtosis is estimated using bootstrapping. ```R # (5) Description of serving size data # with uncertainty on skewness and kurtosis estimated by bootstrap # data(groundbeef) serving <- groundbeef$serving descdist(serving, boot=11) ``` -------------------------------- ### Fit Pareto Distribution using MME in R Source: https://lbbe-software.github.io/fitdistrplus/articles/fitdistrplus_vignette.html Fits a Pareto distribution to the 'Loss' variable in the 'danishuni' dataset using the Method of Moments Estimation (MME). It specifies the order of moments to match and provides starting values and bounds for the parameters. ```R memp <- function(x, order) mean(x^order) fdanish.P.MME <- fitdist(danishuni$Loss, "pareto", method = "mme", order = 1:2, memp = "memp", start = list(shape = 10, scale = 10), lower = c(2+1e-6, 2+1e-6), upper = c(Inf, Inf)) ``` -------------------------------- ### Fit Truncated Gamma Distribution using MLE Source: https://lbbe-software.github.io/fitdistrplus/articles/FAQ.html Fits a truncated gamma distribution to a dataset using the maximum likelihood estimation (MLE) method. This example demonstrates fixing the upper bound and lower bound parameters while estimating shape and rate. ```R fit.NM.2P <- fitdist( data = x, distr = "tgamma", method = "mle", start = list(shape = 10, rate = 10), fix.arg = list(upp = Inf, low=x0), lower = c(0, 0), upper=c(Inf, Inf)) ``` -------------------------------- ### Describe and Plot Ground Beef Serving Sizes Source: https://lbbe-software.github.io/fitdistrplus/reference/groundbeef.html Calculates summary statistics and generates a plot for the serving sizes from the groundbeef dataset. Requires the 'serving' variable to be loaded. ```r serving <- groundbeef$serving descdist(serving) plotdist(serving) ```