I need to add variables to imputed data sets built using mice()
and then use as.mids()
to reassemble them into a mids
object for later analysis. However, when I use complete()
on the rebuilt mids
object, I find that many of the values in the new variable added to the dataset have become NA.
library(mice)
d1 = as.data.frame(matrix(rnorm(100), nrow = 10))
missingness = matrix(as.logical(rbinom(100,1,.2)), ncol = 10)
d1[which(missingness, arr.ind = T)] = NA #replace some values with NA
d.mids = mice(d1, printFlag = F) #make the imputations
d.long = complete(d.mids, "long", T) #extract the original dataset and the imputed ones
added = data.frame(rowSums(d.long[,3:12])) #make a new column
d.long.aug = cbind(d.long,added) #add it to the data.frame
d.remids = as.mids(d.long.aug) #turn it back into a mids object
d.relong = complete(d.remids,"long",T) #extract it from the mids object
sum(is.na(d.long.aug[11:30,13])) #0, unless a variable failed to impute due to collinearity
sum(is.na(d.relong[11:30,13])) #should be the same as previous value, but almost never is
In the above example, I created a new long data.frame and applied as.mdids()
to it, but I get the same results if I use cbind
to add the new variable to d.long
, or if I assign the new variable to d.long$added
.
How can I make sure that the values in the new variable stay there after I reassemble the mids
object?