首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >置信区间mice R包出错

置信区间mice R包出错
EN

Stack Overflow用户
提问于 2021-03-25 10:56:51
回答 1查看 49关注 0票数 1

我尝试执行的每个人的代码都在2.5.3节的"Flexible Imputation of Missing Data 2ed“一书中找到,它计算了两种估算方法的置信区间。问题是我不能重现结果,因为结果总是NaN

以下是代码

代码语言:javascript
复制
require(mice)

# function randomly draws artificial data from the specified linear model

create.data <- function(beta = 1, sigma2 = 1, n = 50, run = 1) {
  set.seed(seed = run)
  x <- rnorm(n)
  y <- beta * x + rnorm(n, sd = sqrt(sigma2))
  cbind(x = x, y = y)
}

#Remove some data

make.missing <- function(data, p = 0.5){
  rx <- rbinom(nrow(data), 1, p)
  data[rx == 0, "x"] <- NA
  data
}

# Apply Rubin’s rules to the imputed data

test.impute <- function(data, m = 5, method = "norm", ...) {
  imp <- mice(data, method = method, m = m, print = FALSE, ...)
  fit <- with(imp, lm(y ~ x))
  tab <- summary(pool(fit), "all", conf.int = TRUE)
  as.numeric(tab["x", c("estimate", "2.5 %", "97.5 %")])
}

#Bind everything together

simulate <- function(runs = 10) {
  res <- array(NA, dim = c(2, runs, 3))
  dimnames(res) <- list(c("norm.predict", "norm.nob"),
                        as.character(1:runs),
                        c("estimate", "2.5 %","97.5 %"))
  for(run in 1:runs) {
    data <- create.data(run = run)
    data <- make.missing(data)
    res[1, run, ] <- test.impute(data, method = "norm.predict",
                                 m = 2)
    res[2, run, ] <- test.impute(data, method = "norm.nob")
  }
  res
}

res <- simulate(1000)

#Estimate the lower and upper bounds of the confidence intervals per method

apply(res, c(1, 3), mean, na.rm = TRUE)

诚挚的问候

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-25 11:24:24

test.impute()最后一行中的"x"替换为tab$term == "x"

代码语言:javascript
复制
as.numeric( tab[ tab$term == "x", c("estimate", "2.5 %", "97.5 %")])
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66792429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档