Learn R Programming

mcmodule

Framework for building modular Monte Carlo risk analysis models. It extends the capabilities of mc2d to facilitate working with multiple risk pathways, variates and scenarios. It provides tools to organize risk analysis in independent flexible modules, perform multivariate mcnode operations, automate the creation of mcnodes and visualise risk analysis models.

Installation

Install from CRAN:

install.packages("mcmodule")
library("mcmodule")

Install latest development version from GitHub.

# install.packages("devtools")
devtools::install_github("NataliaCiria/mcmodule")

Set up an mcmodel

  1. Create a data frame with input parameter
example_data  <- data.frame(
  category_1 = c("a", "b", "a", "b"),      # Category 1 (e.g., type)
  category_2 = c("blue", "blue", "red", "red"), # Category 2 (e.g., group)
  x_min = c(0.07, 0.3, 0.2, 0.5),          # Minimum value for parameter x
    x_max = c(0.08, 0.4, 0.3, 0.6),          # Maximum value for parameter x
    y = c(0.01, 0.02, 0.03, 0.04)            # Value for parameter y
)
  1. Define the keys that uniquely identify each row in your data
example_data_keys <- list(
  example_data = list(
    cols = names(example_data),             # All columns in the data
    keys = c("category_1", "category_2")   # Unique identifiers for each row
  )
)
  1. Define Monte Carlo node table (mctable) indicating how to build the stochastic nodes (you can use this csv template)
example_mctable <- data.frame(
  mcnode = c("x", "y"),                    # Names of the nodes
  description = c("Probability x", "Probability y"), # Descriptions
  mc_func = c("runif", NA),                # Distribution function for x, none for y
  from_variable = c(NA, NA),               # Source variable (not used here)
  transformation = c(NA, NA),              # Transformation (not used here)
  sensi_analysis = c(FALSE, FALSE)         # Include in sensitivity analysis
)
  1. Write model expression indicating how to combine the parameters
example_exp <- quote({
  result <- x * y                     # Calculate result as product of x and y
})
  1. Build the mcmodule with eval_module(), creating the stochastic nodes and evaluating the expression
example_mcmodule <- eval_module(
  exp = c(example = example_exp),          # Model expression(s)
  data = example_data,                     # Input data
  mctable = example_mctable,               # Node definitions
  data_keys = example_data_keys            # Data keys for matching
)
  1. Once you have created a mcmodule object, you can use other package functions to summarize and visualise mcnodes, calculate totals, and combine them with other mcmodules
# Summarize the 'result' node
mc_summary(example_mcmodule, "result")

# Get 'result' aggregated by category 1
example_mcmodule<-example_mcmodule%>%
  agg_totals(
    mc_name = "result",
    agg_keys = c("category_1")
  )

# Print aggregated 'result'
example_mcmodule$node_list$result_agg$summary

# visualise the mcmodule
mc_network(example_mcmodule, legend = TRUE)

Further documentation and examples can be found in the vignette and in the introduction article.

Citations

If you use mcmodule in your research, please cite:

Ciria, N. (2025). mcmodule: Modular Monte Carlo Risk Analysis. R package version 1.1.0. https://nataliaciria.com/mcmodule/

Acknowledgements

mcmodule was developed with support from:

Views and opinions expressed are however those of the author(s) only and do not necessarily reflect those of the European Union or REA. Neither the European Union nor the granting authority can be held responsible for them.

Copy Link

Version

Install

install.packages('mcmodule')

Monthly Downloads

286

Version

1.2.0

License

GPL (>= 3)

Issues

Pull Requests

Stars

Forks

Maintainer

Natalia Ciria

Last Published

March 2nd, 2026

Functions in mcmodule (1.2.0)

mc_keys

Extract Key Columns from Monte Carlo Nodes
mc_match

Match Two Monte Carlo Nodes
imports_data_keys

Example Data Keys for Animal Imports Risk Assessment
mcmodule_corr

Calculate Correlation Coefficients Between Inputs and Outputs
mcnode_na_rm

Replace NA and Infinite Values in mcnode Objects
mcmodule_converg

Analyse Monte Carlo Simulation Convergence
mc_match_data

Match Monte Carlo Node with Data Frame
mc_network

Create Interactive Network Visualisation
reset_mctable

Reset Monte Carlo Inputs Table
reset_data_keys

Reset Data Keys
imports_exp

Expression for Calculating Import Infection Probability
prevalence_region

Regional Pathogen Prevalence Data
set_mctable

Set or Get Monte Carlo Inputs Table
set_data_keys

Set or Get Global Data Keys
mcmodule_to_matrices

Convert Monte Carlo Module to Matrices
mcmodule_dim_check

Check Dimension Compatibility of Monte Carlo Nodes
mcmodule_info

Get Comprehensive Monte Carlo Module Information
mcmodule_to_mc

Convert Monte Carlo Module to mc2d Objects
which_mcnode_inf

Find mcnodes with Infinite Values
visNetwork_edges

Generate Formatted visNetwork Edge Table
trial_totals

Trial Probability and Expected Counts
visNetwork_nodes

Generate Formatted Network Node Table for Visualisation
which_mcnode

Find mcnodes Matching a Condition
wif_match

Match Datasets with Differing Scenarios
which_mcnode_na

Find mcnodes with Missing Values
test_sensitivity

Test Sensitivity Data for Pathogens
mc_summary

Summarise Monte Carlo Node Values
tidy_mcnode

Convert mcnode to Long Format for Plotting
at_least_one

Combine Probabilities Assuming Independence
animal_imports

Example Animal Import Data
check_mctable

Validate and Prepare mctable Data Frame
get_edge_table

Generate Edge Table for Network Visualisation
combine_modules

Combine Two mcmodule Objects
add_prefix

Add Prefix to mcnode Names
agg_totals

Aggregate mcnode Values Across Groups
create_mcnodes

Create mcnodes from Data and Configuration Table
eval_module

Evaluate Monte Carlo Model Expressions
add_group_id

Add Group Identifiers to Data Frame
get_node_list

Create Node List from Model Expression
get_mcmodule_nodes

Get Nodes from Monte Carlo Module
imports_mcmodule

Example Monte Carlo Module for Animal Imports Risk Assessment
imports_mctable

Example Monte Carlo Input Table for Import Risk Assessment
get_node_table

Generate Node Table for Network Visualisation
imports_data

Merged Import Data for Risk Assessment
keys_match

Match and Align Keys Between Datasets
mc_plot

Plot Monte Carlo Node Distribution with Boxplot and Scatter Points
mc_filter

Filter mcnode Variates by Condition