This vignette demonstrates a simulation study of educational
inequalities in major depressive disorder (MDD) using the
MicSim package. The simulation uses sample data derived
from the study by Lepe et al. (2024),
which used data from the Lifelines Cohort Study.
In this vignette we will take you through a standard
MicSim workflow. First, we define the simulation framework
and the initial population, then we specify transition rates, build the
model and run the simulation. Lastly, we process and analyse the
output.
The code uses the object API introduced in MicSim 4.0.0: a model is built as a value, checked, simulated and converted in one pipeline.
# loading libraries
library(MicSim)
library(knitr)
library(dplyr)
library(tidyr)
library(ggplot2)
# Clearing the environment
rm(list = ls())
invisible(gc())We start with defining the simulation horizon (in a yyyymmdd format). Next, we define the desired sample size and minimum and maximum ages. In this example, sample size is kept intentionally small to reduce the computation time. A larger population would lead to better, more reliable results, but cannot be implemented in this example.
startDate <- 20180101
endDate <- 20651231
simHorizon <- c(startDate, endDate)
N <- 1000
minage <- 18
maxage <- 65The state space defines the attributes that characterise the simulated individuals and the values each attribute can take. In this case individuals are characterised by sex (male or female), education (low or high) and health status (NoMDD or MDD).
Usually, for a simulation of a life course, death is a risk an individual will always be exposed to. However, there may be simulations where you don’t want to expose individuals to death, such as in this vignette. You then don’t define any absorbing state.
stateSpace <- state_space(
health = c("NoMDD", "MDD"),
education = c("Low", "High"),
sex = c("Male", "Female")
)
stateSpace## $health
## [1] "NoMDD" "MDD"
##
## $education
## [1] "Low" "High"
##
## $sex
## [1] "Male" "Female"
##
## attr(,"class")
## [1] "micsim_state_space"
For the user, the definition of the initial population is largely left up to their needs and preference. Here we create birthdates for a cohort born in the year 2000 and then assign a baseline prevalence of MDD as estimated from empirical data (see Lepe et al. 2024).
Next, we split the population equally among sex and education and assign the initial states.
set.seed(1234)
birthDates <- runif(N, min = getInDays(20000101), max = getInDays(20001231))
prev <- c(
"Low/Male" = 0.0122,
"Low/Female" = 0.0191,
"High/Male" = 0.0014,
"High/Female" = 0.0022
)
initStates <- names(prev) |>
lapply(function(group) {
sample(
x = paste0(c("MDD/", "NoMDD/"), group),
prob = c(prev[[group]], 1 - prev[[group]]),
size = N / 4, replace = TRUE
)
}) |>
unlist()getInDays() and getInDateFormat() convert
between yyyymmdd dates and days since 1 January 1970 on the
Gregorian calendar. Since version 4.0.0, MicSim works with exact dates
in this way throughout the simulation, including the time windows over
which it integrates the rates. Earlier versions approximated a year as
365.25 days and a month as 30.42 days.
Based on these initial states, we can then create an initial population with birthDates reformatted to yyyymmdd format. The initial population should then look like the one in table below.
initPop <- data.frame(
ID = 1:N,
birthDate = getInDateFormat(birthDates),
initState = initStates,
stringsAsFactors = FALSE
)
initPop |>
head() |>
kable("pipe", caption = "**Example of what initPop should look like**")| ID | birthDate | initState |
|---|---|---|
| 1 | 20000211 | NoMDD/Low/Male |
| 2 | 20000815 | NoMDD/Low/Male |
| 3 | 20000810 | NoMDD/Low/Male |
| 4 | 20000815 | NoMDD/Low/Male |
| 5 | 20001110 | NoMDD/Low/Male |
| 6 | 20000821 | NoMDD/Low/Male |
We only define two sets of rates:
We begin by estimating the transition rates using the observed data. We then generate counterfactual rates under the assumption that individuals with low education have the same quality of social contacts as individuals with high education. This allows us to assess the potential impact of addressing modifiable factors that contribute to educational inequalities in MDD.
In the original study we estimated these rates separately by sex,
education level, and age group (see Lepe et al.
2024). The dataset rates_mdd_groups contains these
estimates at the midpoint of each age group, for the observed rates and
for the counterfactual scenario in which people with low education have
the same quality of social contacts as people with high education. As in
the original study, we obtain a rate for any exact age by fitting a
curve through the estimates for each group.
rates <- rates_mdd_groups
rates |>
head(n = c(6, 8)) |>
kable("html", caption = "**Annual transition rates by age group (midpoints)**")| age | incidence_lo_m | incidence_lo_f | incidence_hi_m | incidence_hi_f | remission_lo_m | remission_lo_f | remission_hi_m |
|---|---|---|---|---|---|---|---|
| 19.5 | 0.0110705 | 0.0141253 | 0.0040992 | 0.0052742 | 0.1658747 | 0.1857702 | 0.1865013 |
| 23.5 | 0.0097389 | 0.0124282 | 0.0036031 | 0.0046214 | 0.1950131 | 0.2106789 | 0.2112272 |
| 28.5 | 0.0091906 | 0.0117232 | 0.0033943 | 0.0043603 | 0.1409138 | 0.1629504 | 0.1637859 |
| 33.5 | 0.0075718 | 0.0097128 | 0.0027937 | 0.0035770 | 0.1863446 | 0.2034726 | 0.2040731 |
| 38.5 | 0.0068146 | 0.0087467 | 0.0025065 | 0.0032115 | 0.1727154 | 0.1918016 | 0.1924804 |
| 43.5 | 0.0065535 | 0.0084073 | 0.0024021 | 0.0031070 | 0.1818538 | 0.1996606 | 0.2002872 |
In MicSim 4.0.0, a rate function declares the time inputs it needs.
It can use age (age), calendar time (calTime),
time since the relevant state variable last changed
(duration), or any combination of these. MicSim matches the
inputs by name and supplies them in fractional years. The MDD incidence
and remission rates in this example depend only on age, so their
functions take age as their sole argument.
Functions that take inputs must be vectorised. For example, if a function receives three ages, it must return three rates in the same order. A constant rate can be specified with a function that takes no arguments and returns a single number.
When MicSim builds the model, it checks the argument names and tests
whether the functions return the expected number of values. The optional
validate() step evaluates the rates on a grid of whole
ages, calendar years and durations to catch evaluation errors and
missing or negative values.
In this example, fit_rate_curve() fits a curve through
the age-group estimates of one rate column. As in the original study,
for incidence we use a straight line, as incidence falls steadily with
age. For remission we use a quadratic curve, which smooths over the
larger variation between age groups. The function returns the fitted
curve as a function of exact age, which is zero before age 18, so
changes in MDD status can start at age 18.
# Fit a curve through the age-group estimates and return a function for all ages.
fit_rate_curve <- function(rate, group_age, shape) {
estimates <- data.frame(age = group_age, rate = rate)
if (shape == "line") {
b <- coef(lm(rate ~ age, data = estimates))
function(age) ifelse(age < 18, 0, b[1] + b[2] * age)
} else if (shape == "quadratic") {
b <- coef(lm(rate ~ age + I(age^2), data = estimates))
function(age) ifelse(age < 18, 0, b[1] + b[2] * age + b[3] * age^2)
}
}
# Skip the age column and keep one function per rate column.
rateFn <- list()
for (column in names(rates)[-1]) {
shape <- if (grepl("remission", column)) "quadratic" else "line"
rateFn[[column]] <- fit_rate_curve(rates[[column]], rates$age, shape)
}Next, we assign these functions to the corresponding state transitions. Note that we define transitions between full composite states, not only along one attribute: a transition may depend on any combination of attributes from the state space. Any transition not defined here is impossible and will not occur.
groups <- expand.grid(
education = c("Low", "High"),
sex = c("Male", "Female"),
stringsAsFactors = FALSE
)
# Match the education and sex codes in the rate-table column names.
groupKey <- function(row) {
paste0(if (row$education == "Low") "lo" else "hi", "_",
if (row$sex == "Male") "m" else "f")
}
build_transitions <- function(prefix = "") {
seq_len(nrow(groups)) |>
lapply(function(k) {
row <- groups[k, ]
key <- groupKey(row)
well <- paste("NoMDD", row$education, row$sex, sep = "/")
ill <- paste("MDD", row$education, row$sex, sep = "/")
list(
transition(well, ill,
rateFn[[paste0(prefix, "incidence_", key)]]),
transition(ill, well,
rateFn[[paste0(prefix, "remission_", key)]])
)
}) |>
unlist(recursive = FALSE) |>
unname()
}
observedTransitions <- build_transitions()
length(observedTransitions)## [1] 8
Building the model puts the pieces together and checks them against each other.
model <- micsim_model(
state_space = stateSpace,
transitions = do.call(
transitions, observedTransitions),
population = initPop,
horizon = simHorizon,
max_age = maxage
)
model## <micsim_model>
## state space : health x education x sex = 8 transient state(s)
## absorbing : none (life courses end at max age)
## transitions : 8 (from 8 declaration(s))
## population : 1000 individual(s)
## horizon : 20180101 to 20651231, max age 65
## subsystems : none
In this example, we consider a counterfactual case, for which we also
define transitions. These are the same; the only difference is between
the transition rates. So we rebuild the transition set from the
cf_ columns of the rate table and keep everything else.
We pass a seed to ensure reproducibility, and then simulate educational inequalities in depression under observed conditions. We first run the main simulation and then the counterfactual (cf) simulation.
Both runs receive the same seed. Every individual draws from their own random-number stream, derived from the seed and their ID, so the two scenarios are driven by the same random numbers (common random numbers): someone whose rates are the same in both scenarios lives the same life in both, and the difference between the scenarios mainly reflects the change in rates rather than Monte Carlo noise.
simpop <- model |> validate() |> simulate(seed = 1234)
cf_simpop <- cf_model |> validate() |> simulate(seed = 1234)
simpop## <micsim_result> MicSim 4.0.0
## 455 event(s) among 1,000 individual(s)
## horizon: 20180101 to 20651231, max age 65
## seed : 1234
## reestimation: 8 transition(s), observed/expected 0.82 to 1.25 (see $reestimation, plot())
## as.data.frame() for the population, as_long() for episodes
After the standard workflow required to run MicSim, the
data can be processed in different ways depending on what one is
interested in.
In this example, we first convert the output to long format, where each row represents a specific episode that an individual experienced. We additionally create variables that indicate the age at the start and end of each episode, as well as a variable indicating whether the data is from the observed or counterfactual simulation. For convenience, the output from both simulations is merged into one data frame, which is then used for further analysis.
Note that you don’t need to supply as_long() with any
arguments, because the result already carries its model, and the model
knows the state space and the horizon.
clamp_ages <- function(long, label) {
long |>
mutate(
agestart = pmin(pmax(getAgeInDays(Tstart, birthDate) / 365.25,
minage), maxage),
agestop = pmin(pmax(getAgeInDays(Tstop, birthDate) / 365.25,
minage), maxage),
sim = label
)
}
simpop_long <- simpop |> as_long() |> clamp_ages("Observed")
cf_simpop_long <- cf_simpop |> as_long() |> clamp_ages("Counterfactual")
mydata <- simpop_long |>
bind_rows(cf_simpop_long) |>
mutate(
sim = factor(sim, levels = c("Observed", "Counterfactual")),
table_order = case_when(
sim == "Observed" & education == "High" ~ 0,
sim == "Observed" & education == "Low" ~ 1,
sim == "Counterfactual" & education == "Low" ~ 2
)
)In this study, we aimed to simulate the development of educational inequalities in MDD across the life course, and to estimate the potential impact of intervening on modifiable factors. In this example, we focus on the educational inequalities in both the age-specific prevalence of MDD and the life course prevalence of MDD. It should be noted that we are not limited to only assessing the prevalence of MDD. For example, in the publication by Lepe et al. (2024) we also look at the age of onset of MDD and the duration of MDD episodes.
We calculate the age-specific prevalence by dividing the number of people with MDD at each whole year of age by the total size of that subgroup (N = 250). These values are then plotted for easier interpretation.
We clearly show that individuals with low education are more likely to experience MDD than individuals with high education, which agrees with the literature. We would also expect the female curves to lie above the male curves throughout, but here the lines cross within each education level. This crossover is simply Monte Carlo noise due to the number of synthetic individuals in the simulation (N = 1000). In the published study we avoided this problem by simulating 500000 individuals, but that size is too computationally heavy for this example.
prev <- minage:maxage |>
lapply(function(i) {
simpop_long |>
filter(health == "MDD", agestart <= i, agestop >= i) |>
group_by(sex, education) |>
summarise(prev = n() / (N * .25) * 100, .groups = "keep") |>
mutate(age = i) |>
ungroup()
}) |>
bind_rows()
prev |>
ggplot() +
geom_line(
aes(age, prev, color = sex, linetype = education),
linewidth = 1
) +
scale_y_continuous(breaks = c(1, 2, 3, 4, 5)) +
labs(
y = "Prevalence of MDD %",
x = "Age (years)",
colour = "Sex",
linetype = "Education"
) +
theme_bw() +
theme(
legend.position = "right",
legend.box.margin = margin(0, 0, 0, 0),
plot.title.position = "plot",
plot.caption.position = "plot",
plot.margin = margin(0, 0, 0, 0)
)Lastly, we calculate life-course prevalence, which is the proportion of people who experience MDD at any point in their life, using both the observed rates and the counterfactual rates. The code here filters by Episode <= 2 to avoid duplicate individuals. This works as people can only transition between the two states, so anyone with depression will have had it in either their first or second episode.
Consistent with earlier findings, those with low education are more likely than those with high education to experience MDD at least once. In the counterfactual scenario, life-course prevalence falls for the low-education group, but it still remains well above the level observed for the high-education group.
mydata |>
filter(Episode <= 2, health == "MDD", !is.na(table_order)) |>
group_by(sim, education, sex) |>
summarise(proportion_MDD = round(n() / (N * .25) * 100, 1),
.groups = "drop") |>
pivot_wider(
names_from = c(sex), names_glue = "{sex} (n%)",
values_from = proportion_MDD
) |>
rename(Scenario = sim, Education = education) |>
kable()| Scenario | Education | Female (n%) | Male (n%) |
|---|---|---|---|
| Observed | High | 16.0 | 12.4 |
| Observed | Low | 32.0 | 29.2 |
| Counterfactual | Low | 27.6 | 24.8 |