我有缺少组件的数据,所以我运行了鼠标算法(来自包鼠标).该函数返回一个.mids对象,我想将其拆分为训练和测试数据集以评估模型拟合.我希望训练和测试数据也是.mids形式,以便它们可以与各种其他功能(如池)结合使用,以根据Rubin的规则调整标准误差.
这是我的尝试,我只是从数据中删除行来获得训练集:
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中的行数而没有调整其他东西).
任何帮助将非常感激.
最佳答案 一种方法是遍历完整的数据集,然后将mira类分配给列表,这应该允许池化. (这就是老鼠::: 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