【发布时间】:2020-10-01 16:18:33
【问题描述】:
我正在努力将 MICE 用于数据集。有一个变量绝对取决于另一个变量,我无法弄清楚如何让 MICE 仅在一个变量中估算 一些 缺失值(而让其他变量真正缺失)。
例如,我有一个关于性别、怀孕状态和结果的数据集。 只有女性可以怀孕,所以如果缺少“怀孕”但主题是男性,那么我不想在那里估算值。
但我确实想为女性赋予怀孕的价值。所有变量(包括性别和结果)都有一些缺失。
我已阅读此处'R', 'mice', missing variable imputation - how to only do one column in sparse matrix 的建议,并尝试在鼠标中使用“where”选项。
但使用“在哪里”似乎并不能估算所有的性结果?
例如;
library(mice)
library(tidyverse)
library(haven)
library(janitor)
# create some data
sex <- c("m","f","m","f","m",NA,NA,"f","f","m","f","f","m","m","f","m")
preg <- c(NA,"not_preg",NA,NA,NA,NA,"preg","not_preg",NA,"not_preg","preg",NA,NA,NA,NA)
outcome <- c(1,0,1,0,0,NA,NA,0,0,1,0,1,1,0,0)
df <- cbind(sex,preg,outcome) %>% as_tibble() %>% mutate(sex=as_factor(sex)) %>% mutate(preg=as_factor(preg))
# look at what's missing
md.pattern(df)
df %>% tabyl(sex,preg)
df %>% tabyl(preg)
# Try to impute over everything to show mice working
mice_a <- mice(df, m=2, maxit=2, seed=3,method="pmm")
df_imp_a <- complete(mice, action="long", include = FALSE)
df_imp_a %>% filter(.imp==1) %>% tabyl(sex,preg) # this has imputed that some men are pregnant (understandably,but not what I want!
df_imp_a %>% filter(.imp==1) %>% tabyl(sex) #but everyone has a sex imputed
df_imp_a %>% filter(.imp==1) %>% tabyl(preg)
# Try to use the 'where' option
# b. Using it with a 'blank' where as proof of principle
grid_b <- is.na(df) #this is just default
mice_b <- mice(df, m=2, maxit=2, seed=3,method="pmm",where=grid_b)
df_imp_b <- complete(mice_b, action="long", include = FALSE)
df_imp_b %>% filter(.imp==1) %>% tabyl(sex,preg) #same problem of pregnant men (obviously, haven't changed anything yet)
df_imp_b %>% filter(.imp==1) %>% tabyl(sex) # but at least everyone has a sex imputed
df_imp_b %>% filter(.imp==1) %>% tabyl(preg)
# c. Making a proper grid of data that I do and don't want imputed
grid_c <- df %>%
mutate(preg=case_when(
sex=="f" & is.na(preg)==TRUE ~ TRUE,
TRUE ~ FALSE
)) %>%
mutate(sex=is.na(sex)) %>%
mutate(outcome=is.na(outcome))
grid_c
grid_c %>% tabyl(preg) # so we are looking for 4 imputed values of 'preg' (so I've done it right -- there are 4 females with unknown pregnancy status)
mice_c <- mice(df,m=2,maxit=2,seed=3,method="pmm",where=grid_c)
df_imp_c <- complete(mice_c,action="long",include=FALSE)
df_imp_c %>% filter(.imp==1) %>% tabyl(sex,preg) # now I have no pregnant men -- which is good!
df_imp_c %>% filter(.imp==1) %>% tabyl(sex) # but I am missing sex for one person??
df_imp_c %>% filter(.imp==1) %>% tabyl(preg) # have imputed all the pregnancy data that I wanted through -- only 7 NAs (for the 7 men)
我如何设法告诉老鼠我只想估算某个列中的某些行而不是所有行?但是我确实想要估算另一列的所有行?为什么“where”选项的行为不像我想象的那样?
非常感谢所有帮助!谢谢。
【问题讨论】: