R:数据插补除以性别
R: data imputation divided by gender
我有数据集
mydat=structure(list(sex = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), emotion = c(20L,
15L, 49L, NA, 34L, 35L, 54L, 45L), IQ = c(101L, 98L, 105L, NA,
123L, 120L, 115L, NA)), .Names = c("sex", "emotion", "IQ"), class = "data.frame", row.names = c(NA,
-8L))
所以我想使用 MICE 库进行插补。
mydat <- mice(mydat)
complete(mydat)
但是我怎样才能同时对所有变量按性别分别进行插补?
性别1为男,2为女
您可以使用 dplyr
中的 group_by()
:
library(dplyr)
library(mice)
mydat <- mydat %>%
group_by(sex) %>%
mice() %>%
complete()
一个更费力的解决方案:
prep = mice(mydat, maxit = 0)
imp_meth = prep$method
imp_meth[c("sex")] = ""
pred_m = prep$predictorMatrix
pred_m[, c("IQ", "emotion")] = 0
set.seed(123)
imputed <- mice(mydat, method = imp_meth, predictorMatrix = pred_m)
complete(imputed)
我有数据集
mydat=structure(list(sex = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), emotion = c(20L,
15L, 49L, NA, 34L, 35L, 54L, 45L), IQ = c(101L, 98L, 105L, NA,
123L, 120L, 115L, NA)), .Names = c("sex", "emotion", "IQ"), class = "data.frame", row.names = c(NA,
-8L))
所以我想使用 MICE 库进行插补。
mydat <- mice(mydat)
complete(mydat)
但是我怎样才能同时对所有变量按性别分别进行插补?
性别1为男,2为女
您可以使用 dplyr
中的 group_by()
:
library(dplyr)
library(mice)
mydat <- mydat %>%
group_by(sex) %>%
mice() %>%
complete()
一个更费力的解决方案:
prep = mice(mydat, maxit = 0)
imp_meth = prep$method
imp_meth[c("sex")] = ""
pred_m = prep$predictorMatrix
pred_m[, c("IQ", "emotion")] = 0
set.seed(123)
imputed <- mice(mydat, method = imp_meth, predictorMatrix = pred_m)
complete(imputed)