I'm building a predictive model and am using the mice
package for imputing NAs in my training set. Since I need to re-use the same imputation scheme for my test set, how can I re-apply it to my test data?
# generate example data
set.seed(333)
mydata <- data.frame(a = as.logical(rbinom(100, 1, 0.5)),
b = as.logical(rbinom(100, 1, 0.2)),
c = as.logical(rbinom(100, 1, 0.8)),
y = as.logical(rbinom(100, 1, 0.6)))
na_a <- as.logical(rbinom(100, 1, 0.3))
na_b <- as.logical(rbinom(100, 1, 0.3))
na_c <- as.logical(rbinom(100, 1, 0.3))
mydata$a[na_a] <- NA
mydata$b[na_b] <- NA
mydata$c[na_c] <- NA
# create train/test sets
library(caret)
inTrain <- createDataPartition(mydata$y, p = .8, list = FALSE)
train <- mydata[ inTrain, ]
test <- mydata[-inTrain, ]
# impute NAs in train set
library(mice)
imp <- mice(train, method = "logreg")
train_imp <- complete(imp)
# apply imputation scheme to test set
test_imp <- unknown_function(test, imp$unknown_data)