[This article was first published on r on Everyday Is A School Day, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.MICE always felt like magic to me So I tried rebuilding it from scratch in R to understand it better. Lots of mistakes and help along the way, but my version ended up close to the mice package. Might be just luck. Still learning, but here are my messy notes! Motivations We used mulitple imputation by chained equations (MICE) quite often in imputing missing data in many occasion, but I never really understood the mechanism behind it except that it appears magical! I want to see if I can build this from scratch as a mean to understand the foundation of MICE so that at least it will give me the illusion of understanding. Join me in my messy journey of trying to code it from the ground up (FYI, I’m not coding OLS or MLE from the ground up…), and let’s see if we can create some “magic” here! This is going to be a bumpy one with lots of coding, and maybe less of mathematical formulae. I’ll try my best to provide a TL;DR for each section so that we can get a high level view as well. Buckle up! And oh, Happy Halloween! What a better time to look at magical recipes of statistics! Let’s go!Objectives: What Is MICESimulate Our DGPThe Procedure To Impute And Create Multiple DatasetsPool them!Opportunities For ImprovementLessons LearntWhat Is MICE TL;DR: fill in each gap several times with plausible random guesses, analyse each completed dataset, then combine the results.When data are missing, the tempting fix is to plug in one best guess, like the mean. The problem is that a single guess pretends we know the missing value exactly, so our standard errors come out too small. MICE takes a different approach: it fills in each missing value with a plausible random draw, and does this several times to create multiple complete datasets. The differences between those datasets capture our uncertainty about what the missing values really were.The “chained equations” part is how those draws are made. Instead of one giant model for all variables at once, MICE fits a simple regression for each incomplete variable, using all the others as predictors, and cycles through them, each one feeding its freshly imputed values into the next. After a few rounds, the imputations settle down. Finally, we analyse each completed dataset and pool the results with Rubin’s rules. Simulate Our DGP Alright let’s simulate our data generating process (the truth) and add in missing data mechanism to create our dataset that we want to impute from (imagine this is the dataset that we have and we want to apply mice on it).library(tidyverse)library(broom)set.seed(1)n