在估算数据框中包含 ID 变量

问题描述 投票:0回答:2

我正在使用

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
作为变量包含在每个估算数据框中?

r missing-data r-mice
2个回答
4
投票

有两种方法。首先,只需将

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 年手册说:“用户可以指定自定义预测器矩阵,从而有效地调节每个变量的预测器数量。例如,假设 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

您还可以阻止小鼠输入变量,但由于它不包含缺失值,因此没有必要(小鼠会自动跳过它)。


0
投票

Niek 的答案是正确的方法,但我也注意到字符变量会在“常量”的基础上自动捕获并从

mice
的预测矩阵中删除(可能是因为
mice
将字符向量视为完全
NA
)。因此,在我看来,数据集中包含的任何字符类型变量都将通过插补步骤传递,而不用作插补的预测变量。

© www.soinside.com 2019 - 2024. All rights reserved.