Introduction
Welcome to the mathmodels package! This is a
comprehensive and user-friendly R toolkit designed for practitioners and
researchers in the field of mathematical modeling. At its core,
mathmodels embodies the philosophy of “simplifying the
complex,” encapsulating sophisticated mathematical algorithms into
intuitive functions. This allows you to focus on model construction and
interpretation, rather than getting bogged down in implementation
details.
The mathmodels package is developed as a companion to
the book “Mathematical
Modeling: Algorithms and Programming Implementation” (China Machine
Press). The current version (0.0.14) spans the full modeling workflow:
data cleaning and multiple imputation,
statistical inference, multivariate
statistics, a rich suite of evaluation
algorithms (weighting, TOPSIS, fuzzy evaluation, DEA,
inequality measures, …), prediction models (grey,
Markov, regression, time series), interpolation and curve
fitting, and differential equation / epidemic
models.
Key Features
-
Data Cleaning — missing-value diagnostics
(
na_summary(),na_mcar_test()for Little’s MCAR test) with heatmap / bar visuals; imputation via simple fills (impute(): group mean / median / mode, linear & spline interpolation, constants), a unified model-based framework (impute_model(): kNN, linear regression, decision trees), and multiple imputation (impute_multiple(): FCS chained equations with pmm/norm for numeric columns and logreg/polyreg for categorical ones) with Rubin’s-rules pooling (rubin_pool()for scalar estimates,pool_fit()for lm/glm fits, including the Barnard-Rubin small-sample df adjustment); outlier detection and handling (outlier()); Excel-stylepivot_table(). -
Statistical Inference — tidy hypothesis tests:
t-test / Wilcoxon, ANOVA / Kruskal-Wallis, ANCOVA, correlation,
chi-square, normality and variance-homogeneity tests
(
stat_*()), each returning one tidy row per test with effect sizes and.byslice grouping; generic bootstrap and permutation frameworks;export_table()renders results as Word/LaTeX three-line tables. -
Multivariate Statistics — PCA
(
mv_pca()), EFA (mv_efa()), hierarchical and k-means clustering with validity metrics (mv_hclust(),mv_kmeans(),mv_cluster_metrics()), discriminant analysis (mv_discrim()), correspondence analysis (mv_corresp()), MDS (mv_mds()), canonical and partial correlation (mv_cancor(),mv_pcor()), all with tidy components andplot_mv_*()visuals. -
Evaluation Models — AHP, Entropy weighting, CRITIC,
CV, PCA and factor-analysis weighting (
weight_*()family), weight combination (combine_weights()), TOPSIS, Grey Relational Analysis (GRA), Rank Sum Ratio (RSR), Fuzzy Comprehensive Evaluation (FCE) with themf_*membership-function family, Data Envelopment Analysis (CCR/BCC/SBM, Malmquist), inequality measures (Gini, Theil index), regional economics (LQ/HHI/EG), and coupling coordination / obstacle degree models. -
Prediction Models — grey prediction (GM(1,1),
GM(1,N), DGM(2,1), Verhulst), Markov chain prediction
(
markov_chain(),GM11_markov()), a regression prediction toolkit (reg_lm(),reg_logistic(),reg_poisson(),reg_negbin()with stepwise selection;reg_predict(),reg_diagnostics(),plot_reg_*()), and a lightweight time-series workflow built aroundts_df(as_ts_df(),complete_ts_df()/impute_ts_df(),ts_transform()/ts_back_transform(),ts_test(),ts_stl(),ts_ets(),ts_sarima(),ts_arimax(),ts_forecast(), plusplot_ts*()). -
Interpolation and Curve Fitting — piecewise linear,
cubic spline, polynomial and Hermite interpolation
(
interp_linear(),interp_spline(),interp_poly(),interp_hermite()), plus curve fitting (poly_fit(),curve_fit(),growth_fit()) with automatic starting values for logistic, Gompertz and Michaelis-Menten nonlinear models. -
Differential Equation Models — string-formula
ode_solver()for arbitrary ODE systems; ready-to-use population models (Malthus, Logistic), epidemic compartment models (SI, SIS, SIR, SEIR) and the Lotka-Volterra predator-prey model, all with a unifiedinit+paramsinterface; epidemic visualization (plot_compartments(),plot_incidence(),plot_phase_si(),plot_Rt_estimate()) and metrics (epi_metrics()for R0, peak, attack rate). -
Elegant, Tidyverse-friendly Interface —
standardized argument names,
|>pipes anddplyr/tidyr/ggplot2integration, with data preprocessing (normalization, scaling, indicator direction) handled internally.
Quick Start
To start using mathmodels, first ensure it’s installed
and loaded:
# Install from GitHub (recommended)
remotes::install_github("zhjx19/mathmodels")
# Or install from a local source package
install.packages("mathmodels.tar.gz", repos = NULL, type = "source")Once loaded, you can immediately use its functions. For example,
perform a quick entropy weighting TOPSIS analysis using the built-in
water_quality dataset:
# View example data
water_quality## # A tibble: 20 × 5
## ID O2 PH germ nutrient
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1 4.69 6.59 51 11.9
## 2 2 2.03 7.86 19 6.46
## 3 3 9.11 6.31 46 8.91
## 4 4 8.61 7.05 46 26.4
## 5 5 7.13 6.5 50 23.6
## 6 6 2.39 6.77 38 24.6
## 7 7 7.69 6.79 38 6.01
## 8 8 9.3 6.81 27 31.6
## 9 9 5.45 7.62 5 18.5
## 10 10 6.19 7.27 17 7.51
## 11 11 7.93 7.53 9 6.52
## 12 12 4.4 7.28 17 25.3
## 13 13 7.46 8.24 23 14.4
## 14 14 2.01 5.55 47 26.3
## 15 15 2.04 6.4 23 17.9
## 16 16 7.73 6.14 52 15.7
## 17 17 6.35 7.58 25 29.5
## 18 18 8.29 8.41 39 12.0
## 19 19 3.54 7.27 54 3.16
## 20 20 7.44 6.26 8 28.4
# Preprocess data: handle centered and interval-type indicators
df = water_quality |>
mutate(
# Optimal PH is 7 -> Centered-type positive
PH = rescale_middle(PH, 7),
# Optimal nutrient is 10-20 -> Interval-type positive
nutrient = rescale_interval(nutrient, 10, 20)
)Calculate weights using the Entropy Method (normalization is handled
internally). First, specify the indicator directions: since the
indicator columns PH and nutrient have been pre-normalized, their
directions are set to NA to avoid repeating the
normalization process.
idx = c("+", NA, "-", NA)
res = weight_entropy(df[-1], idx)
res$w # View calculated weights## O2 PH germ nutrient
## 0.3153202 0.1813149 0.3506929 0.1526721
When performing TOPSIS (which has built-in normalization), you need to specify the indicator directions in order to correctly determine the positive and negative ideal solutions.
## 1 2 3 4 5 6 7 8
## 0.3841556 0.4852199 0.5021310 0.5084128 0.4226200 0.3945085 0.5502261 0.6258551
## 9 10 11 12 13 14 15 16
## 0.7260529 0.7138447 0.8091923 0.6159619 0.6007565 0.1593096 0.4974685 0.4250799
## 17 18 19 20
## 0.5565555 0.4815844 0.3070290 0.7098355
The obtained result is the relative closeness score.
The same tidy workflow extends to the other modules. For instance, multiple imputation of missing values followed by Rubin’s-rules pooling of a regression model:
set.seed(1)
d = data.frame(x = rnorm(40), z = rnorm(40))
d$y = 0.5 * d$x + rnorm(40)
d$x[c(3, 9)] = NA # introduce missingness
imps = impute_multiple(d, .cols = x, m = 5, maxit = 3, seed = 2) # 5 imputations
fits = lapply(imps, \(dat) lm(y ~ x, dat)) # fit each
pool_fit(fits) # pooled coefficients (Rubin's rules)## Pooled estimates (Rubin's rules)
## # A tibble: 2 × 7
## term estimate std_error lcl ucl p_value fmi
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 0.134 0.133 -0.135 0.403 0.319 0.0520
## 2 x 0.277 0.153 -0.0325 0.587 0.0778 0.0533
Getting Help and In-Depth Learning
This Vignette offers just a glimpse into the capabilities of
mathmodels. For a thorough understanding of all algorithms,
their detailed principles, function usage, and practical case studies,
we highly recommend consulting our comprehensive online
companion manual:
📘 mathmodels Package Manual - Simplifying Mathematical Modeling (Online Book)
This online manual serves as the definitive documentation for the
mathmodels package. It consolidates content from the
package vignettes and covers the evaluation algorithms, statistical
inference, multivariate statistics, data cleaning, prediction models and
differential equation models, with R implementations and extensive
examples, making it your best resource for learning and using this
package.
We hope mathmodels proves to be a valuable and reliable
companion on your journey through mathematical modeling and scientific
research.