r - 在 R 中使用 .mids 对象创建训练数据集

标签 r training-data r-mice

我有缺少组件的数据,所以我运行了鼠标算法(来自包 mice)。该函数返回一个 .mids 对象,我想将其拆分为训练数据集和测试数据集以评估模型拟合。我希望训练和测试数据也是 .mids 格式,以便它们可以与各种其他功能相结合,例如 pool根据鲁宾规则调整标准误差。

这是我的尝试,我只是从数据中删除行以获得训练集:

library(mice)
data <- mice(nhanes,m=2,maxit=5,seed=1)

set.seed(2)
rand <- (1:nrow(nhanes))*rbinom(nrow(nhanes),size=1,prob=0.7)
train <- data
train$data <- train$data[rand,]

但是,如果我尝试使用这些数据运行模型:
pool(with(train, lm(bmi ~ chl + age)))

我遇到一个错误,指出它试图用 7 替换 9 行(大概是因为我减少了 train$data 中的行数而不调整其他内容)。

任何帮助将非常感激。

最佳答案

一种方法是循环遍历 complete数据集,然后分配 mira类到列表,这应该允许 pool ing。 (这正是 mice:::with.mids 所做的)

无采样示例

library(mice)

imp <- mice(nhanes,m=2, maxit=5, seed=1)

# With in-built pooling
pool(with(imp, lm(bmi ~ chl + age)))

# Pooled coefficients:
# (Intercept)         chl         age 
# 21.38496144  0.05975537 -3.40773396 
# 
# Fraction of information about the coefficients missing due to nonresponse: 
# (Intercept)         chl         age 
#   0.6186312   0.1060668   0.7380962 

# looping manually
mod <- list(analyses=vector("list", imp$m))

for(i in 1:imp$m){
  mod$analyses[[i]] <- lm(bmi ~ chl + age, data=complete(imp, i))
}

class(mod) <- c("mira", "matrix")
pool(mod)

# Pooled coefficients:
# (Intercept)         chl         age 
# 21.38496144  0.05975537 -3.40773396 
# 
# Fraction of information about the coefficients missing due to nonresponse: 
# (Intercept)         chl         age 
#   0.6186312   0.1060668   0.7380962 

看起来没问题,所以添加一个采样程序
mod <- list(analyses=vector("list", imp$m))

set.seed(1)
for(i in 1:imp$m){
  rand <- (1:nrow(nhanes))*rbinom(nrow(nhanes),size=1,prob=0.7)
  mod$analyses[[i]] <- lm(bmi ~ chl + age, data=complete(imp, i)[rand,])
}

class(mod) <- c("mira", "matrix")
pool(mod)

# Pooled coefficients:
# (Intercept)         chl         age 
# 21.72382272  0.06468044 -4.23387415 
# 
# Fraction of information about the coefficients missing due to nonresponse: 
# (Intercept)         chl         age 
#   0.1496987   0.4497024   0.6101340 

关于r - 在 R 中使用 .mids 对象创建训练数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37025996/

相关文章:

r - R : Take 3 中 MI 数据的描述性统计

R:mice() 如何知道要插补哪个变量?

r - 如何向日期添加或减去数字?

R似乎忽略了下划线之后的变量名部分

machine-learning - 机器学习中,开发后可以将开发集添加到训练集中吗?

machine-learning - SVM 分类 - 每个类别的最小输入集数量

r - 多重插补数据集的 MICE 数量。

按行平均超过增加号。在 mutate : dplyr R 内使用 for 循环的列数

R:在单个因子变量上加宽多个列

matlab - 从分割输出构建训练图像的最有效方法是什么?