The previous article presented the missingness mechanisms, together with the exploration of missing values in R, in a simulated cohort. This article uses the data from the same simulation and examines statistical techniques for imputing the missing values.
Applying statistical imputation methods to simulated data
In the example below we will see how the distribution of HbA1c changes with each imputation method, comparing it with the true distribution, which we know from before the values were removed. The comparison is made on the mean HbA1c and on the percentage of patients with HbA1c above 7%.
rSimulating the cohort and introducing the missing values31 lines
library(tidyverse); library(naniar); library(ggmice); library(mice)
theme_set(theme_minimal(base_family = "sans", base_size = 12) +
theme(panel.grid.minor = element_blank(), plot.title.position = "plot"))
navy <- "#1F2A44"; pink <- "#D5487F"; grey <- "#8A93A6"
set.seed(2026)
n <- 800
d <- tibble(
age = round(rnorm(n, 64, 10)),
sex = factor(sample(c("F", "M"), n, replace = TRUE)),
dm_years = round(rexp(n, 1 / 8)),
education = factor(sample(c("primary", "secondary", "tertiary"), n, replace = TRUE,
prob = c(0.35, 0.45, 0.20)),
levels = c("primary", "secondary", "tertiary")),
smoking = factor(rbinom(n, 1, plogis(-1.2 - 0.5 * (education == "tertiary"))),
labels = c("no", "yes")),
bmi = round(rnorm(n, 30, 5), 1),
sbp = round(128 + 0.5 * (age - 64) + 0.7 * (bmi - 30) + rnorm(n, 0, 13)),
ldl = round(rnorm(n, 105, 30)),
egfr = round(pmax(15, 95 - 0.9 * (age - 64) - 1.2 * dm_years + rnorm(n, 0, 14))),
hba1c = round(6.4 + 0.07 * dm_years + 0.02 * (age - 64) + 0.03 * (bmi - 30) + rnorm(n, 0, 1.0), 1)
)
d_obs <- d |>
mutate(
ldl = if_else(runif(n) < 0.08, NA, ldl), # MCAR
hba1c = if_else(runif(n) < plogis(-2.4 + 0.08 * (age - 64) + 0.12 * dm_years), # MAR: ηλικία, έτη από διάγνωση
NA, hba1c),
smoking = if_else(runif(n) < plogis(-2.8 + 1.3 * (education == "primary")), # MAR: μόρφωση
NA, smoking),
egfr = if_else(runif(n) < plogis(-2.0 - 0.06 * (egfr - 75)), NA, egfr) # MNAR: η ίδια η τιμή
)truth <- d |> summarise(mean_hba1c = mean(hba1c), pct_above7 = 100 * mean(hba1c > 7))
truth |> mutate(across(everything(), ~ round(.x, 2)))# A tibble: 1 × 2
mean_hba1c pct_above7
<dbl> <dbl>
1 6.96 44.4In the complete dataset, before the missing values are introduced, the mean HbA1c is 6.96% and 44.4% of patients have an HbA1c above 7%. These are the reference values against which each method will be compared.
Complete case analysis
The default of every statistical package, when it meets a missing value, is to ignore it. R's mean(x, na.rm = TRUE) and summary() are computed on the patients who happened to have a value. So that the results of every method that follows are comparable, a small function is defined that returns, for a vector of HbA1c, the number of available values, the mean, its standard error, the 95% confidence interval and the percentage of values above 7%.
describe_hba1c <- function(x, label) {
x <- x[!is.na(x)]
m <- mean(x); se <- sd(x) / sqrt(length(x))
tibble(method = label, n = length(x), mean = m, se = se,
ci_low = m - 1.96 * se, ci_high = m + 1.96 * se, pct_above7 = 100 * mean(x > 7))
}
fmt <- function(tbl) mutate(tbl, across(where(is.double), ~ round(.x, 2)))results <- bind_rows(
describe_hba1c(d$hba1c, "Πλήρη δεδομένα (αληθής τιμή)"),
describe_hba1c(d_obs$hba1c, "Complete case analysis"))
fmt(results)# A tibble: 2 × 7
method n mean se ci_low ci_high pct_above7
<chr> <int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Πλήρη δεδομένα (αληθής τιμή) 800 6.96 0.04 6.88 7.04 44.4
2 Complete case analysis 603 6.78 0.04 6.7 6.87 39.1The analysis rests on about 600 of the 800 patients. The mean HbA1c appears lower than the true one, 6.78 against 6.96, and the percentage of patients off target smaller, 39% against 44%. The 95% confidence interval, 6.70 to 6.87, does not contain the true value, so patients with normal HbA1c values appear more numerous than they are. The deviation is explained by the missingness mechanism. The patients without a measurement are the older ones and those with the most years since diagnosis, that is, the patients with the highest expected HbA1c, so the subset that remains does not represent the cohort. Complete case analysis is unbiased only under MCAR, which the exploration in the previous article had ruled out for HbA1c.
Simple imputation with the mean (mean imputation)
Replacing every gap with the mean of the available observations remains widespread because it is simple and preserves the sample size. For this particular question its weakness is obvious, since the mean of the completed dataset is by definition equal to the mean of the complete cases, so the bias remains exactly the same. What changes is the shape of the distribution and, above all, the standard error.
rMean imputation and comparison of the distributions11 lines
d_mean <- d_obs |> mutate(hba1c = replace_na(hba1c, mean(hba1c, na.rm = TRUE)))
both <- bind_rows(παρατηρούμενα = d_obs, `μέση τιμή` = d_mean, .id = "dataset") |>
filter(!is.na(hba1c))
ggplot(both, aes(x = hba1c, fill = dataset, colour = dataset)) +
geom_histogram(aes(y = after_stat(density)), binwidth = 0.25, position = "identity",
alpha = 0.45, colour = NA) +
geom_density(fill = NA, linewidth = 0.9, adjust = 1.3) +
scale_fill_manual(values = c(navy, pink)) +
scale_colour_manual(values = c(navy, pink)) +
labs(x = "HbA1c (%)", y = "πυκνότητα", fill = NULL, colour = NULL) +
theme(legend.position = "top")
results <- bind_rows(results, describe_hba1c(d_mean$hba1c, "Mean imputation"))
fmt(results)# A tibble: 3 × 7
method n mean se ci_low ci_high pct_above7
<chr> <int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Πλήρη δεδομένα (αληθής τιμή) 800 6.96 0.04 6.88 7.04 44.4
2 Complete case analysis 603 6.78 0.04 6.7 6.87 39.1
3 Mean imputation 800 6.78 0.03 6.72 6.85 29.5The mean is the same as before and equally biased. The standard error, however, is smaller and the confidence interval narrower, for two reasons. The denominator of the standard error is now 800 instead of 600, because the sample grew, and the standard deviation fell because a quarter of the values are identical. The result is a narrower interval around the same wrong value, that is, greater certainty about a mistaken conclusion. The percentage above 7% shifted arbitrarily, depending on whether the mean happened to fall above or below the threshold.
Multiple imputation
Multiple imputation (MI) replaces each gap not with one value but with m different ones, drawn from a model that describes the distribution of HbA1c given the patient's other variables. For example, a 75-year-old patient with 20 years since diagnosis receives values from the distribution found in similar patients with an available measurement. This gives m completed datasets, each dataset is analysed separately and the m estimates are combined with Rubin's rules (1987), which add to the standard error the variance of the estimates between the datasets, that is, the uncertainty about the lost values that single imputation ignores. In R the established implementation is the mice package (van Buuren & Groothuis-Oudshoorn 2011) and the procedure has three steps: generating the m datasets with mice(), analysing each one with with() and combining them with pool().
Step 1, generating the completed datasets
The command mice(d_obs) would run with the defaults too, but it is advisable for the analyst to take the following into account.
The variables of the imputation model. The rule is to include all those that will be used in the analysis and, in addition, those that predict either the missingness or the value of the incomplete variable. In the previous article the logistic regression showed that age and years since diagnosis predict the missingness of HbA1c, so their presence is mandatory, because they are what makes the MAR assumption plausible. The remaining variables are included as auxiliary ones, because any information they carry about HbA1c improves the imputation. An imputation model is rarely harmed by more variables, but it is seriously harmed by the wrong omissions.
The number m of completed datasets, where a practical rule is at least equal to the percentage of incomplete cases (White et al. 2011), here 50. The number of iterations of the algorithm, set with the maxit argument, here 10 instead of the default 5, and its adequacy is checked afterwards with the convergence plot. The seed is also set, an arbitrary integer that fixes the random number generator, so that the analysis gives the same results on every run.
imp <- mice(d_obs, m = 50, maxit = 10, seed = 2026, printFlag = FALSE)The object imp contains the 50 completed datasets and the information on how they were produced. The first thing to check is which method was applied to each variable.
imp$method[imp$method != ""] smoking ldl egfr hba1c
"logreg" "pmm" "pmm" "pmm" For the continuous variables mice automatically chose pmm, predictive mean matching, and for smoking logreg, logistic regression. Multiple imputation is the framework, that is, the strategy of the m datasets, the separate analysis and the combination with Rubin's rules. PMM is one of the methods by which the values inside each dataset are generated, and the method argument of mice() allows a different method per variable. The main options are, for continuous variables, pmm and norm (Bayesian linear regression with a stochastic term), for binary ones logreg, for categorical ones polyreg and for ordered ones polr, while cart (classification and regression trees) and rf (random forest) apply to every type of variable and capture non-linear relationships and interactions without their having to be specified in advance. The same multiple imputation could be run with any of these by changing only method, and the choice is the analyst's decision, not the software's.
For HbA1c, PMM is appropriate because its distribution is skewed and bounded, so norm could give values outside the clinically possible range, while its relationships with the other variables are approximately linear and do not require the flexibility of cart and rf. Because it is the default, it does not need to be declared explicitly. PMM is presented in detail in a separate article.
To show what the imputation produced at the level of the patient, the first patient with a missing HbA1c is selected. The first table shows that patient's characteristics, and the second summarises the 50 HbA1c values assigned to them, one in each completed dataset.
i <- which(is.na(d_obs$hba1c))[1]
d_obs[i, c("age", "dm_years", "bmi")]# A tibble: 1 × 3
age dm_years bmi
<dbl> <dbl> <dbl>
1 54 10 26.1imputed_i <- imp$imp$hba1c[as.character(i), ] |> unlist()
round(summary(imputed_i), 2) Min. 1st Qu. Median Mean 3rd Qu. Max.
4.90 6.30 7.10 7.06 7.70 9.10 The patient is 54 years old, with 10 years since diagnosis and a BMI of 26.1. The 50 values received range from 4.9 to 9.1, with a median of 7.1, that is, in the range found in patients with similar characteristics and an available measurement. Each of them is a value that has actually been measured in one of the patient's donors. Had mean imputation been applied, the patient would have received the value 6.78 all 50 times.
Checks before the analysis
Before the completed datasets are used, it is checked whether the algorithm has converged. The algorithm is iterative: in each iteration it imputes all the variables again using the values of the previous one, and it needs some iterations before the imputations stabilise. The trace plot shows, for each of the 50 datasets, the mean and the standard deviation of the imputed HbA1c values at each of the 10 iterations.
plot_trace(imp, vrb = "hba1c") +
scale_colour_viridis_d(option = "mako", end = 0.85, guide = "none")
Each line is one completed dataset and each of its points the value of the mean, on the left, or of the standard deviation, on the right, of the imputed HbA1c at the corresponding iteration. Convergence means that the 50 lines oscillate around the same level from start to finish, without rising or falling systematically and without separating into groups. Here the mean hovers around 7.35 and the standard deviation around 1.05 at every iteration, and the lines intertwine, so ten iterations were sufficient. If the lines showed an upward or downward slope, or if some stayed consistently above the others, more iterations would be needed, with a larger maxit.
The next check compares the distribution of the imputed values with that of the observed ones. Under MAR they are expected to differ, and here the difference has a specific direction: the imputed values should be higher. If they were the same as the observed ones, the model would not have made use of age and years since diagnosis.
ggmice(imp, aes(x = hba1c, group = .imp)) +
geom_density(linewidth = 0.4) +
scale_colour_manual(values = c(navy, alpha(pink, 0.3)), guide = "none") +
labs(x = "HbA1c (%)", y = "πυκνότητα")
Steps 2 and 3, analysis and pooling
with() applies the same model to each of the 50 datasets and pool() combines the 50 results with Rubin's rules. pool() accepts only statistical models, not simple functions such as mean(), so for the mean HbA1c a linear model without explanatory variables is used, lm(hba1c ~ 1), whose intercept is exactly the mean. Likewise, for the percentage of patients with HbA1c above 7% a logistic regression without explanatory variables is used, glm(I(hba1c > 7) ~ 1), whose intercept is the percentage on the log-odds scale and is converted to a percentage with plogis().
rAnalysis and pooling with Rubin's rules11 lines
fit_mean <- with(imp, lm(hba1c ~ 1))
fit_prop <- with(imp, glm(I(hba1c > 7) ~ 1, family = binomial))
m_est <- summary(pool(fit_mean), conf.int = TRUE)
p_est <- summary(pool(fit_prop), conf.int = TRUE)
results <- bind_rows(results,
tibble(method = "Multiple imputation (PMM, m = 50)", n = 800,
mean = m_est$estimate, se = m_est$std.error,
ci_low = m_est$`2.5 %`, ci_high = m_est$`97.5 %`,
pct_above7 = 100 * plogis(p_est$estimate)))
fmt(results)# A tibble: 4 × 7
method n mean se ci_low ci_high pct_above7
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Πλήρη δεδομένα (αληθής τιμή) 800 6.96 0.04 6.88 7.04 44.4
2 Complete case analysis 603 6.78 0.04 6.7 6.87 39.1
3 Mean imputation 800 6.78 0.03 6.72 6.85 29.5
4 Multiple imputation (PMM, m = 50) 800 6.93 0.04 6.84 7.02 45.0The estimates of the mean HbA1c and of the percentage off target are now close to the true values, which the 95% confidence interval contains.
Comparing the methods over repetitions
A single run is not enough to compare methods, because the difference between two estimates may be due to chance. The simulation is repeated 200 times, each time with new data and new missing values, and for each method the bias is recorded, that is, the mean deviation from the true value, together with the coverage, that is, the percentage of repetitions in which the 95% confidence interval contains the true value. Coverage is the critical measure, because it checks whether the confidence interval tells the truth about its own uncertainty. Four approaches are compared below: complete case analysis, mean imputation, multiple imputation with only the variables that predict the missingness, and multiple imputation with all the available variables. For reasons of computing time, m = 10 is used in the repetitions.
rSimulation code50 lines
gen_data <- function(n = 800) {
d <- tibble(
age = round(rnorm(n, 64, 10)),
sex = factor(sample(c("F", "M"), n, replace = TRUE)),
dm_years = round(rexp(n, 1 / 8)),
education = factor(sample(c("primary", "secondary", "tertiary"), n, replace = TRUE,
prob = c(0.35, 0.45, 0.20)),
levels = c("primary", "secondary", "tertiary")),
smoking = factor(rbinom(n, 1, plogis(-1.2 - 0.5 * (education == "tertiary"))),
labels = c("no", "yes")),
bmi = round(rnorm(n, 30, 5), 1),
sbp = round(128 + 0.5 * (age - 64) + 0.7 * (bmi - 30) + rnorm(n, 0, 13)),
ldl = round(rnorm(n, 105, 30)),
egfr = round(pmax(15, 95 - 0.9 * (age - 64) - 1.2 * dm_years + rnorm(n, 0, 14))),
hba1c = round(6.4 + 0.07 * dm_years + 0.02 * (age - 64) + 0.03 * (bmi - 30) + rnorm(n, 0, 1.0), 1)
)
obs <- d |> mutate(
ldl = if_else(runif(n) < 0.08, NA, ldl),
hba1c = if_else(runif(n) < plogis(-2.4 + 0.08 * (age - 64) + 0.12 * dm_years), NA, hba1c),
smoking = if_else(runif(n) < plogis(-2.8 + 1.3 * (education == "primary")), NA, smoking),
egfr = if_else(runif(n) < plogis(-2.0 - 0.06 * (egfr - 75)), NA, egfr))
list(full = d, obs = obs)
}
mean_ci <- function(x) { x <- x[!is.na(x)]; m <- mean(x); se <- sd(x) / sqrt(length(x)); c(m, se) }
pool_mean <- function(imp) { s <- summary(pool(with(imp, lm(hba1c ~ 1)))); c(s$estimate, s$std.error) }
one_rep <- function() {
g <- gen_data(); truth <- mean(g$full$hba1c); dd <- g$obs
cca <- mean_ci(dd$hba1c)
mn <- mean_ci(replace_na(dd$hba1c, mean(dd$hba1c, na.rm = TRUE)))
mi_min <- pool_mean(mice(dd |> select(hba1c, age, dm_years), m = 10, printFlag = FALSE))
mi_all <- pool_mean(mice(dd, m = 10, printFlag = FALSE))
tibble(method = c("Complete case analysis", "Mean imputation",
"MI, μόνο ηλικία και έτη από διάγνωση", "MI, όλες οι μεταβλητές"),
est = c(cca[1], mn[1], mi_min[1], mi_all[1]),
se = c(cca[2], mn[2], mi_min[2], mi_all[2]),
truth = truth)
}
set.seed(2026)
sims <- map_dfr(1:200, ~ one_rep())
lv <- c("Complete case analysis", "Mean imputation",
"MI, μόνο ηλικία και έτη από διάγνωση", "MI, όλες οι μεταβλητές")
res <- sims |>
mutate(covered = abs(est - truth) < 1.96 * se, dev = est - truth) |>
group_by(method) |>
summarise(bias = mean(dev), lo = quantile(dev, 0.025), hi = quantile(dev, 0.975),
coverage = 100 * mean(covered), .groups = "drop") |>
mutate(method = factor(method, levels = lv))rBias and coverage per method10 lines
res |>
mutate(label = sprintf("coverage %.0f%%", coverage), is_mi = str_starts(method, "MI")) |>
ggplot(aes(y = fct_rev(method))) +
geom_vline(xintercept = 0, colour = grey, linetype = 2) +
geom_errorbar(aes(xmin = lo, xmax = hi, colour = is_mi), width = 0.25, orientation = "y") +
geom_point(aes(x = bias, colour = is_mi), size = 2.5) +
geom_text(aes(x = max(hi) + 0.02, label = label), hjust = 0, size = 3.4, colour = navy) +
scale_colour_manual(values = c(`TRUE` = pink, `FALSE` = navy), guide = "none") +
scale_x_continuous(expand = expansion(mult = c(0.05, 0.4))) +
labs(x = "bias (μονάδες HbA1c)", y = NULL)
Complete case analysis and mean imputation have the same bias, as explained. Multiple imputation with only the two variables that determine the missingness is enough to remove the bias, confirming that what matters is to include the right variables, not many of them, while adding the rest as auxiliary ones slightly improves precision at no cost. In both versions the confidence intervals contain the true value with the frequency they state.
Reporting the handling of missing values in studies
The handling of missing values affects the results and is reported with the same completeness as any other methodological choice. The Methods section states the percentage of missing values per variable and the percentage of complete cases, the missingness mechanism assumed and its justification on the basis of the study design, the imputation method and the software with its version, the number m of completed datasets and of iterations, the variables included in the imputation model with explicit mention of the auxiliary ones, and the way in which convergence and the plausibility of the imputations were checked. The results present the main analysis with multiple imputation and the complete case analysis as a comparison, and the code is made available. The absence of these elements is among the most frequent reasons for revision in observational studies (Mainzer et al. 2024).
References
- Carpenter JR, Kenward MG (2013). Multiple Imputation and its Application. Wiley.
- Madley-Dowd P, Hughes R, Tilling K, Heron J (2019). The proportion of missing data should not be used to guide decisions on multiple imputation. Journal of Clinical Epidemiology, 110, 63–73.
- Mainzer RM, Moreno-Betancur M, Nguyen CD, Simpson JA, Carlin JB, Lee KJ (2024). Gaps in the usage and reporting of multiple imputation for incomplete data, findings from a scoping review of observational studies addressing causal questions. BMC Medical Research Methodology, 24, 193.
- Morris TP, White IR, Royston P (2014). Tuning multiple imputation by predictive mean matching and local residual draws. BMC Medical Research Methodology, 14, 75.
- Rubin DB (1987). Multiple Imputation for Nonresponse in Surveys. Wiley.
- van Buuren S (2018). Flexible Imputation of Missing Data, 2nd ed. Chapman & Hall/CRC.
- van Buuren S, Groothuis-Oudshoorn K (2011). mice, multivariate imputation by chained equations in R. Journal of Statistical Software, 45(3), 1–67.
- White IR, Royston P, Wood AM (2011). Multiple imputation using chained equations, issues and guidance for practice. Statistics in Medicine, 30(4), 377–399.


