How import the saved mice/mids object from a file

Viewed 407

I am looking for a way to export the mice object to a file such that I could load it back in the future for further analysis. I found some information about using miceadds::write.mice.imputation to save the data to local files. I also find a similar post in Exporting multiple imputed objects with MICE But the accepted answer in that post does not really solve the problem, write.mice.imputation could save the imputed data, variable list, and so on to the file but it does not save the information to reconstruct a mice object.

library(mice)
library(miceadds)

imp <- mice::parlmice(data=nhanes, n.core = 4, n.imp.core = 1, m=3, maxit = 50, print=T)
write.mice.imputation(mi.res=imp, name="mice_imp1")

I saw the folder mice_imp1 created in local and some data saved in there as well. But using the following code to load the data does not regenerate the mice object

library(mice)
library(miceadds)

oldData <- read.table("mice_imp1/mice_imp1__IMPDATA1.dat")
stripplot(oldData, pch=20, cex=2) # this line gives error

the last line does not compile since oldData is just data but not a mice object.

1 Answers

On the one hand, write.mice.imputation stores each of the multiple imputed data sets in .dat files, on the other hand it stores the "mids" object as an .Rdata file. While you want the latter you load the former.

library(mice)
library("miceadds")

impdir <- "./mice_imp1"
imp <- mice::parlmice(data=nhanes, n.core=4, n.imp.core=1, m=3, maxit=50, print=T)
write.mice.imputation(mi.res=imp, name=impdir, mids2spss=F)
ls()  ## whats in the wrkspace?
# [1] "imp"    "impdir"
rm(imp)  ## remove the mice data

Looking into the directory what objects are stored and we probably want the mice_imp1.Rdata file,

file.info(list.files("./mice_imp1", full.names=T))[,1, drop=F]
# mice_imp1/mice_imp1.Rdata                14105
# mice_imp1/mice_imp1__DATALIST.Rdata        734
# mice_imp1/mice_imp1__IMP_LIST.txt          108
# mice_imp1/mice_imp1__IMP_SUMMARY.txt      3875
# mice_imp1/mice_imp1__IMPDATA1.dat          365
# mice_imp1/mice_imp1__IMPDATA2.dat          363
# mice_imp1/mice_imp1__IMPDATA3.dat          363
# mice_imp1/mice_imp1__IMPDATA4.dat          365
# mice_imp1/mice_imp1__IMPMETHOD.csv          37
# mice_imp1/mice_imp1__LEGEND.txt             20
# mice_imp1/mice_imp1__LONG.dat             1878
# mice_imp1/mice_imp1__PREDICTORMATRIX.csv    70
# mice_imp1/mice_imp1__VARNAMES.txt           20

which we may load.

load("mice_imp1/mice_imp1.Rdata")
ls()
# [1] "impdir" "mi.res"

It comes as "mi.res" with class "mids",

class(mi.res)
# [1] "mids"

and can be plotted.

stripplot(get("mi.res"), pch=20, cex=2)

enter image description here

Related