0

I have a global environment with many dataframes which should be imputed with mice library(mice). In order to first calculate the prediction matrices I did (with the help of some other people) the following:

library(mice)
PredMatr= list()
Myls<-ls(sorted=F)[eapply(.GlobalEnv, class)=="data.frame"]
try (for (i in 1:length(Myls))  {
    PredMatr[[i]]=quickpred(get(Myls[i]), mincor=.1)
})

This creates a very nice list with all the prediction matrices. The next step however is even a bit more complicated. I would like to do something similar to do the imputation. I want to loop through the dataframes like before. However now I would like the operation to be an imputation, referring to the predictor matrix from the previous list. I tried:

dfimpls= list()
try (for (i in 1:length(Myls))  {
    dfimpls[[i]]=mice(get(Myls[i]), m=5, maxit = 5, method='cart',predictorMatrix=PredMatr[i])
})

The syntax is however incorrect, giving me the following error:

Error : predictorMatrix not a matrix

With:

dfimpls= list()
try (for (i in 1:length(Myls))  {
    dfimpls[[i]]=mice(get(Myls[i]), m=5, maxit = 5, method='cart',predictorMatrix=as.matrix(PredMatr[i]))
})

I get:

Error : Missing row/column names in predictorMatrix
Tom
  • 2,173
  • 1
  • 17
  • 44
  • is `PredMatr[i]` a `matrix` or `data.frame`? If you just change it to `predictorMatrix=as.matrixPredMatr[i])` does that help? – John Paul Dec 07 '18 at 15:36
  • 1
    Please show us data of underlying data frames so we can reproduce your issue as required by a [MCVE]. See [this](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Parfait Dec 07 '18 at 15:45
  • It should really be a matrix.. I added you suggestion to the answer (although it probably only applies if `PredMatr[i]` was not a matrix but a df right?) – Tom Dec 07 '18 at 15:46
  • @JohnPaul Is it possible that it is again an ordering issue? In other words, that the list of prediction matrices `PredMatr` is in a different order than the `Myls` ? – Tom Dec 07 '18 at 16:06
  • @Tom You should check to make sure that the column names in the `PredMatr`s are the same as those expected by `mice()`. If the names are different it might not now how to do the prediction - but I am not familiar with this package. – John Paul Dec 07 '18 at 16:13
  • A question: Why do you need a prediction matrix for Mice? I thought mice imputation is just as simple as `mice(df)`. – Corey Levinson Dec 07 '18 at 16:44
  • 1
    @CoreyLevinson https://stefvanbuuren.name/fimd/sec-toomany.html – Tom Dec 07 '18 at 16:46
  • 1
    Have you tried `predictorMatrix=PredMatr[[i]]`? – Ian Wesley Dec 07 '18 at 16:55
  • @ Ian Wesley That actually worked, thank you so much! – Tom Dec 08 '18 at 11:29

0 Answers0