An R package providing a versatile toolkit for mathematical modeling, developed as a companion to the book Mathematical Modeling: Algorithms and Programming Implementation (China Machine Press). It focuses on implementing rigorous algorithms in a user-friendly manner.
Current Version (0.0.14) introduces a data-cleaning toolkit — missing-value diagnostics with Little’s MCAR test (na_mcar_test()), missingness visuals (plot_na_heatmap(), plot_na_bar()), simple and model-based imputation (impute(), impute_model() with kNN / linear regression / decision trees), multiple imputation by FCS chained equations (impute_multiple()) with Rubin’s-rules pooling (rubin_pool(), pool_fit(); Barnard-Rubin small-sample df), and outlier handling (outlier()) — plus the Excel-style pivot_table(). Together with the previous release’s tidy statistical inference toolkit (stat_*() tests, bootstrap and permutation frameworks, export_table()), the multivariate statistics toolkit (mv_*()), the factor-analysis weighting weight_fa(), and the renamed weight_* / mf_* families. All this builds on the regression prediction toolkit, time-series workflow, epidemic modeling, differential equation models, grey prediction, Markov chain models, interpolation and curve fitting, and a rich suite of evaluation methods (AHP, Entropy, CRITIC, PCA, TOPSIS, Fuzzy, RSR, DEA).
Key Features
-
Data Cleaning (new) — missing-value diagnostics (
na_summary(),na_mcar_test()for Little’s MCAR test) with heatmap / bar visuals; imputation: simple fills (group mean / median / mode, linear & spline interpolation, constants), a unified model-based framework (impute_model()with kNN, linear regression, decision trees), and multiple imputation (impute_multiple(): FCS chained equations, pmm/norm for numeric columns, logreg/polyreg for categorical ones) with Rubin’s-rules pooling (rubin_pool()for scalar estimates,pool_fit()for lm/glm fits, incl. the Barnard-Rubin small-sample df adjustment); every changed cell is recorded for audit. Outlier detection and handling (outlier(): IQR / z-score / Hampel-MAD bounds, set-NA or cap). Excel-stylepivot_table(). -
Multivariate Statistics (new) — 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. -
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; generic bootstrap and permutation frameworks;export_table()renders results as Word/LaTeX three-line tables. -
Evaluation Models — AHP, Entropy weighting, CRITIC, CV, PCA and factor-analysis weighting, TOPSIS, Grey Relational Analysis (GRA), Rank Sum Ratio (RSR), Fuzzy Comprehensive Evaluation (FCE) with the
mf_*family of membership functions, Data Envelopment Analysis (CCR/BCC/SBM, Malmquist), plus inequality measures (Gini, Theil Index), coupling coordination degree, and obstacle degree models. -
Prediction Models —
-
Grey prediction (GM(1,1), GM(1,N), Verhulst), Markov chain prediction (
markov_chain(),GM11_markov()), -
regression prediction toolkit (
reg_lm(),reg_logistic(),reg_poisson(),reg_negbin()with stepwise selection;reg_predict(),reg_diagnostics(),plot_reg_predict(),plot_reg_residuals()), - lightweight time series toolkit built around
ts_df:as_ts_df()for conversion,complete_ts_df()/impute_ts_df()for gap handling,ts_transform()/ts_back_transform()for Box-Cox / log / differencing workflows,ts_test()for stationarity tests,ts_stl()for STL decomposition,ts_ets(),ts_sarima(), andts_arimax()for modeling,ts_forecast()for unified forecasting, plusplot_ts(),plot_ts_forecast(),plot_ts_acf(),plot_ts_pacf(),plot_ts_stl(), andplot_ts_residuals().
-
Grey prediction (GM(1,1), GM(1,N), Verhulst), Markov chain prediction (
-
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 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). -
Tidyverse Integration — Seamlessly works with
|>anddplyr/ggplot2for smooth data manipulation and batch processing.
Installation
Once released on CRAN, install mathmodels with:
install.packages("mathmodels")You can install the latest development version directly from GitHub:
remotes::install_github("zhjx19/mathmodels")Getting Started
library(mathmodels)
# --- AHP (Analytic Hierarchy Process) ---
A = matrix(c(1, 1/2, 4, 3, 3,
2, 1, 7, 5, 5,
1/4, 1/7, 1, 1/2, 1/3,
1/3, 1/5, 2, 1, 1,
1/3, 1/5, 3, 1, 1), byrow = TRUE, nrow = 5)
AHP(A)
# --- Epidemic compartment modeling ---
result = ode_sir(
init = c(S = 990, I = 10, R = 0),
params = c(beta = 0.15, gamma = 0.1), # R0 = 1.5
times = seq(0, 100, by = 0.5))
# Visualize
plot_compartments(result, compartments = c("S", "I", "R"))
# Compute epidemic metrics
metrics = epi_metrics(result, beta = 0.15, gamma = 0.1, N = 1000)
metrics$R0 # basic reproduction number
# --- Time series ---
x = as_ts_df(log(AirPassengers))
fit = ts_sarima(x)
fc = ts_forecast(fit, h = 12)
plot_ts_forecast(x, fc) # forecast with CIs
# --- Statistical inference (tidy in, tidy out) ---
res = stat_t_test(sleep, .cols = extra, group = group)
res # one tidy row: statistic, p, CI, Cohen's d
export_table(res, output = "latex", caption = "Two-sample t-test")
# --- Multivariate statistics ---
r = mv_pca(mtcars, cyl:carb)
plot_mv_scree(r, type = "cum") # cumulative variance screeLearning More
For detailed documentation, tutorials, and in-depth examples on using the mathmodels package, please refer to the comprehensive online manual:
📘 mathmodels Package Manual - Simplifying Mathematical Modeling (Online Book, In Chinese)
This online book is the definitive guide to the package’s functionalities. Currently implemented modules include:
-
Differential equation models: Malthus, Logistic, SI, SIS, SIR, SEIR, Lotka–Volterra with
ode_solver()andode_*()functions; epidemic visualization (plot_compartments(),plot_incidence(),plot_phase_si(),plot_Rt_estimate()) and metrics (epi_metrics()) -
Statistical inference (0.0.13): tidy tests —
stat_describe(),stat_t_test(),stat_wilcox_test(),stat_anova(),stat_kruskal(),stat_ancova(),stat_cor(),stat_chisq(),stat_normality(),stat_hov_test()— all with.byslice grouping and effect sizes; generic frameworksstat_bootstrap(),stat_perm_test();export_table()for Word/LaTeX three-line tables -
Multivariate statistics (0.0.12):
mv_pca(),mv_efa(),mv_hclust(),mv_kmeans(),mv_cluster_metrics(),mv_discrim(),mv_corresp(),mv_mds(),mv_cancor(),mv_pcor()withplot_mv_*()visuals -
Data cleaning (0.0.14):
na_summary(),na_mcar_test()(Little’s MCAR test),plot_na_heatmap()/plot_na_bar(); imputation viaimpute()(group mean/median/mode, linear/spline, constant), the unified model-based frameworkimpute_model()(kNN, linear regression, decision trees), and multiple imputationimpute_multiple()(FCS chained equations) with Rubin’s-rules poolingrubin_pool()/pool_fit(); outlier handling withoutlier()(detect / set NA / cap) -
Pivot table (0.0.14):
pivot_table()for Excel-style aggregation and spreading -
Time series:
ts_df(),as_ts_df(),validate_ts_df(),complete_ts_df(),impute_ts_df(),drop_na_ts_df(),ts_transform(),ts_back_transform(),ts_ets(),ts_sarima(),ts_arimax(),ts_stl(),ts_test(),ts_forecast(); visualization:plot_ts(),plot_ts_acf(),plot_ts_pacf(),plot_ts_forecast(),plot_ts_stl(),plot_ts_residuals() -
Regression prediction:
reg_lm(),reg_logistic(),reg_poisson(),reg_negbin()with stepwise selection;reg_predict(),reg_diagnostics(),plot_reg_predict(),plot_reg_residuals() -
Interpolation & curve fitting:
interp_linear(),interp_spline(),interp_poly(),interp_hermite()for interpolation;poly_fit(),curve_fit(),growth_fit()for curve fitting -
Markov chain prediction:
markov_chain()andGM11_markov() - Indicator data preprocessing
- AHP, Entropy weighting, CRITIC, CV, PCA and factor analysis weighting (
weight_*()family, incl.weight_fa()) - Weight combination techniques (
combine_weights()) - TOPSIS, Grey Relational Analysis (GRA)
- Rank Sum Ratio (RSR), Fuzzy Comprehensive Evaluation (FCE) with the
mf_*membership-function family - Data Envelopment Analysis (CCR/BCC/SBM, Malmquist)
- Inequality Measures (Gini, Theil Index)
- Regional Economics (LQ/HHI/EG Index)
- Coupling coordination degree and obstacle degree