我正在使用library(mice)
来估算丢失的数据。我想要一种方法告诉mice
,ID变量应包含在估算数据集上,但不能用于估算。
例如
#making a silly data frame with missing data
library(tidyverse)
library(magrittr)
library(mice)
d1 <- data.frame(
id = str_c(
letters[1:20] %>%
rep(each = 5),
1:5 %>%
rep(times = 20)
),
v1 = runif(100),
v2 = runif(100),
v3 = runif(100)
)
d1[, -1] %<>%
map(
function(i){
i[extract(sample(1:100, 5, F))] <- NA
i
}
)
这是返回的mids
对象
m1 <- d1 %>%
select(-id) %>%
mice
如何在每个估算的数据帧中包括d1$id
作为变量?
答案 0 :(得分:0)
有两种方法。首先,只需将id
附加到估算数据集
d2 <- complete(m1,'long', include = T) # imputed datasets in long format (including the original)
d3 <- cbind(d1$id,d2) # as datasets are ordered simply cbind `id`
m2 <- as.mids(d3) # and transform back to mids object
这可确保id
在插补过程中没有任何作用,但是有点草率且容易出错。另一种方法是简单地将其从预测变量矩阵中删除。
Van Buuren和Groothuis-Oudshoorn的2011 manual说:“ 用户可以指定自定义的预报器矩阵,从而有效地调节每个变量的预报器数量。例如,假设bmi被认为是不相关的将bmi列中的所有条目设置为零会有效地将其从预测变量集中删除...不会将bmi用作预测变量,但仍会归因于它。“
为此
ini <- mice(d1,maxit=0) # dry run without iterations to get the predictor matrix
pred1 <- ini$predictorMatrix # this is your predictor matrix
pred1[,'id'] <- 0 # set all id column values to zero to exclude it as a predictor
m1 <-mice(d1, pred = pred1) # use the new matrix in mice
您还可以防止鼠标插入变量,但是由于它不包含任何缺失值,因此这不是必需的(鼠标会自动跳过它)。