Skip to content

Instantly share code, notes, and snippets.

@sdaza
Last active May 22, 2017 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdaza/56aef14d725d58e5670c562447f35a84 to your computer and use it in GitHub Desktop.
Save sdaza/56aef14d725d58e5670c562447f35a84 to your computer and use it in GitHub Desktop.
Multilevel imputation using MICE
# load data
load("ex.Rdata")
###################################
# example only using mice package
###################################
library(mice)
imp <- mice(ex, maxit = 0)
mat <- imp$predictorMatrix
meth <- imp$meth
# adjust prediction matrix
mat["frace",] <- 0
mat[c("frace", "cedui", "clinci", "dghealth"), "pid"] <- 0
mat[c("frace"), "pid"] <- -2
# redefine methods
meth["clinci"] <- "pmm"
meth["cedui"] <- "pmm"
meth["frace"] <- "2lonly.pmm"
meth["dghealth"] <- "pmm"
# I get warning messages
imp1 <- mice(ex, m = 1 , predictorMatrix = mat ,
imputationMethod = meth ,
maxit = 2)
# adding male as predictor for frace
mat["frace", "male"] <- 1
# I get an error
imp2 <- mice(ex, m = 1 , predictorMatrix = mat ,
imputationMethod = meth ,
maxit = 2)
##########################
# using miceadds package
##########################
library(miceadds)
imp <- mice(ex, maxit = 0)
mat <- imp$predictorMatrix
meth <- imp$meth
# adjust prediction matrix
mat["frace",] <- 0
mat[c("frace", "cedui", "clinci", "dghealth"), "pid"] <- 0
mat[c("frace"), "pid"] <- 1
mat[c("cedui", "clinci", "dghealth"), "pid"] <- -2
# redefine methods
meth["clinci"] <- "2l.pmm"
meth["cedui"] <- "2l.pmm"
meth["frace"] <- "pmm"
meth["dghealth"] <- "2l.pmm"
meth
# no warning messages
imp3 <- mice(ex, m = 1 , predictorMatrix = mat ,
imputationMethod = meth ,
maxit = 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment