问题描述
我有一个从mice
创建的mids
对象.我想重新编码一些估算的变量并保留mids
对象.我知道我可以使用complete()
将mids
对象转换为长",但是我想保留mids
对象,因为它还有一些其他用途.
I have a mids
object created from mice
. I would like to recode some imputed variables and retain the mids
object. I know that I could convert the mids
object to "long" with complete()
, but I want to keep the mids
object since it has some additional uses.
这是使用nhanes
数据集的示例.运行mice()
会为nhanes
中的变量创建5个估算数据集.我专注于hyp
.
Here's an example using the nhanes
dataset. Running mice()
creates 5 imputed datasets for the variables in nhanes
. I'm focusing on hyp
.
library(mice)
names(nhanes)
nhanes$hyp
#[1] NA 1 1 NA 1 NA 1 1 1 NA NA NA 1 2 1 NA 2 2 1 2 NA 1 1 1
imp <- mice(nhanes, print = FALSE)
imp$imp$hyp
# 1 2 3 4 5
# 1 1 1 1 1 1
# 4 2 1 1 2 2
# 6 1 1 1 1 1
# 10 1 1 1 1 1
# 11 1 1 2 1 1
# 12 1 1 1 1 2
# 16 1 1 2 1 1
# 21 1 1 2 1 1
我该如何重新编码mids
对象imp
内的推导hyp
值(例如1变成5).
How could I recode the imputed hyp
values inside the mids
object imp
(e.g., 1's become 5's).
到目前为止,我唯一的想法是将imp
转换为long,将感兴趣的变量提取到新的数据帧中,重新编码,通过as.mids
转换新的数据帧,然后通过cbind.mids()
放回imp
./p>
My only ideas thus far involves converting imp
to long, extracting the variables of interest into a new dataframe, recoding, converting the new dataframe via as.mids
, then putting back into imp
via cbind.mids()
.
imp_long <- complete(imp, "long", include=T)
hyp <- imp_long[, "hyp"]
hyp2 <- hyp
hyp2[hyp2==1] <- 5
hyp4mids <- data.frame(.imp = rep(0:5, each = nrow(nhanes)),
.id = rep(1:nrow(nhanes), times = 6),
hyp2,
TMP = NA)
hyp4mids <- as.mids(hyp4mids, .imp = 1, .id = 2)
hyp4mids$chainMean <- hyp4mids$chainVar <- array(NA, dim = c(2, 25, 5),
dimnames = list(
c("hyp2", "TMP"),
1:25,
paste0("Chain ", 1:5)))
imp2 <- cbind.mids(imp, hyp4mids)
imp2$imp$hyp2
# 1 2 3 4 5
# 1 5 5 5 5 5
# 4 2 5 5 2 2
# 6 5 5 5 5 5
# 10 5 5 5 5 5
# 11 5 5 2 5 5
# 12 5 5 5 5 2
# 16 5 5 2 5 5
# 21 5 5 2 5 5
它可以工作,但是我认为我应该能够直接在imp
mids对象中修改hyp
.
It works, but I think I should be able to modify hyp
in the imp
mids object directly.
推荐答案
看来,诀窍是修改$ data和$ imp:
It appears that the trick is to modify $data and $imp:
imp <- mice(nhanes, print = FALSE)
l1 <- complete(imp, "long")
table(l1$hyp)
# 1 2
#92 33
imp$data$hyp[imp$data$hyp==1] <- 5
imp$imp$hyp[imp$imp$hyp==1] <- 5
l2 <- complete(imp, "long")
table(l2$hyp)
# 2 5
#33 92
这篇关于重新编码鼠标Mids对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!