Another post from R package misc
! This time, we’ll see how to fit multiple continuous parametric distributions on a vector of data and simulate best-fitting distribution. Under the hood, misc::fit_param_dist
uses a loop of MASS::fitdistr
calls and Kullback-Leibler divergence for checking distribution adequacy.
remotes::install_github("thierrymoudiki/misc")
set.seed(123) n <- 1000 vector <- rweibull(n, 2, 3) # Replace with your vector start <- proc.time()[3] simulate_function <- misc::fit_param_dist(vector) end <- proc.time()[3] print(paste("Time taken:", end - start)) simulated_data <- simulate_function(n) # Generate 100 samples from the best-fit distribution par(mfrow = c(1, 2)) hist(vector, main = "Original Data", xlab = "Value", ylab = "Frequency") hist(simulated_data, main = "Simulated Data", xlab = "Value", ylab = "Frequency")
set.seed(123) n <- 1000 vector <- rnorm(n) # Replace with your vector start <- proc.time()[3] simulate_function <- misc::fit_param_dist(vector) end <- proc.time()[3] print(paste("Time taken:", end - start)) simulated_data <- simulate_function(n) # Generate 1000 samples from the best-fit distribution par(mfrow = c(1, 2)) hist(vector, main = "Original Data", xlab = "Value", ylab = "Frequency") hist(simulated_data, main = "Simulated Data", xlab = "Value", ylab = "Frequency")
# Example usage 1 set.seed(123) n <- 1000 vector <- rlnorm(n) # Replace with your vector start <- proc.time()[3] simulate_function <- misc::fit_param_dist(vector) end <- proc.time()[3] print(paste("Time taken:", end - start)) simulated_data <- simulate_function(n) # Generate 1000 samples from the best-fit distribution par(mfrow = c(1, 2)) hist(vector, main = "Original Data", xlab = "Value", ylab = "Frequency") hist(simulated_data, main = "Simulated Data", xlab = "Value", ylab = "Frequency")
set.seed(123) n <- 1000 vector <- rbeta(n, 2, 3) # Replace with your vector start <- proc.time()[3] simulate_function <- misc::fit_param_dist(vector, verbose=TRUE) end <- proc.time()[3] print(paste("Time taken:", end - start)) simulated_data <- simulate_function(n) # Generate 1000 samples from the best-fit distribution par(mfrow = c(1, 2)) hist(vector, main = "Original Data", xlab = "Value", ylab = "Frequency") hist(simulated_data, main = "Simulated Data", xlab = "Value", ylab = "Frequency")
Bonus: You can develop a package at the command line, by putting this file in the root directory of your package, and typing make
or make help
at the command line. Here’s the Makefile: