0
votes

I am using the mice package to impute data, and I have read about post processing to restrict imputed values. In my dataset, I have data for the same thing as number and as category. I want to impute all the missing values of those data but impute them in the correct cetegory. I have found similar approaches in mice documentation but they give only one range and not many.

Any ideas about this in mice in R?

1
Avoid major edits to the post. - zx8754

1 Answers

1
votes

Here is an reproducable example for what you are trying to achieve. You can use multiple lines of code in post['ageint'] to squeeze the age integer conditionally on the age category. This was based on the documentation found here

require(tidyverse)
require(mice)

set.seed(315)

getAge <- function(range){
  minAge <- str_extract(range,'[0-9]+')
  maxAge <- str_extract(range,'[0-9]+$')
  sample(minAge:maxAge,1)
}

dat <- nhanes2 %>%
  mutate(ageint = map_int(age,~if_else(sample(c(TRUE,FALSE),1),getAge(.x),as.integer(NA))))

init <- mice(dat,m=1,maxit=1, print = FALSE)

post <- init$post

post["ageint"] <- "
                  imp[[j]][data$age[!r[, j]] == '20-39', i] <- squeeze(imp[[j]][data$age[!r[, j]] == '20-39', i], c(20, 39))
                  imp[[j]][data$age[!r[, j]] == '40-59', i] <- squeeze(imp[[j]][data$age[!r[, j]] == '40-59', i], c(40, 59))
                  imp[[j]][data$age[!r[, j]] == '60-99', i] <- squeeze(imp[[j]][data$age[!r[, j]] == '60-99', i], c(60, 99))
"

To illustrate, I have plotted imputation without post-processing and with post-processing. You can see what happens:

imp1 <- mice(dat,seed = 314, print = FALSE)
imp2 <- mice(dat,post=post,seed = 314, print = FALSE)



mice::complete(imp1, action = 'long') %>% mutate(method = 'default') %>%
  bind_rows(mice::complete(imp2,action = 'long') %>% mutate(method = 'with post')) %>%
  ggplot(aes(x = age, y = ageint, color = factor(.imp))) +
  geom_jitter() +
  scale_y_continuous(limits = c(0,100)) +
  facet_grid(~method)

enter image description here