代码之家  ›  专栏  ›  技术社区  ›  aelhak

适用于多重插补数据集的模型结果能否被提取到数据帧中?

  •  1
  • aelhak  · 技术社区  · 7 年前

    是否有可能将多个模型的汇总估计值提取到一个数据框架中,以适合乘以插补数据?

    以下是我如何对完整的案例数据框架(即没有缺失数据)执行此操作的过程——我想做一个类似的过程,以提取适合插补数据的几个模型的类似结果:

    library(tidyverse)
    library(broom)
    library(mice)
    
    data <- nhanes
    sapply(data, function(x) sum(is.na(x))) #check missing data
    data <- data %>% filter(bmi !="NA" & hyp != "NA" & chl != "NA") # remove missing data
    
    out <-c("bmi")
    exp <- c("chl","age","factor(hyp)")
    
    #run models and extract to tidy data frame
    models <- expand.grid(out, exp) %>%
    group_by(Var1) %>% rowwise() %>%
    summarise(frm = paste0(Var1, "~", Var2)) %>%
    group_by(model_id = row_number(),frm) %>%
    do(tidy(lm(.$frm, data = data))) %>%
    mutate(lci = estimate-(1.96*std.error),
         uci = estimate+(1.96*std.error))
    

    下面是使用 mice 只拟合一个回归模型:

    # Impute missing data using mice
    data <- nhanes
    imp <- mice(data, print = F)
    
    #Fit single model
    fit <- with(imp, lm(bmi ~ chl))
    
    #Get pooled estimates
    a <- pool(fit)
    
    summary(a)
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   nghauran    7 年前

    这里的关键点是从 complete(imp, "long") 因为它提供了所有的插补数据集。这样做之后,你必须玩一些游戏 tidyverse broom 特别是功能 nest() tidy() 这在这里非常有用。试试这个:

    library(tidyverse)
    library(broom)
    library(mice)
    data <- nhanes # data
    imp <- mice(data, print = F) # imputation
    # complete data
    data.complete <- complete(imp, "long")  
    glimpse(data.complete) # all the 5 imputations are here
    
    data.complete %>% 
            select(-.id) %>% 
            nest(-.imp) %>%
            mutate(model = map(data, ~lm(bmi ~ chl, data = .)),
                   tidied = map(model, tidy)) %>%
            unnest(tidied) %>%
            filter(term == "chl") %>%
            mutate(adjusted = p.adjust(p.value),
                   lci = estimate-(1.96*std.error),
                   uci = estimate+(1.96*std.error))
    # output
      .imp term   estimate  std.error statistic     p.value   adjusted           lci        uci
    1    1  chl 0.01972747 0.01755024  1.124057 0.272584078 0.45430932 -0.0146709916 0.05412594
    2    2  chl 0.02133664 0.01719462  1.240891 0.227154661 0.45430932 -0.0123648105 0.05503808
    3    3  chl 0.03070542 0.01534959  2.000407 0.057397701 0.22512674  0.0006202261 0.06079062
    4    4  chl 0.04109955 0.02044568  2.010183 0.056281686 0.22512674  0.0010260220 0.08117308
    5    5  chl 0.05448964 0.01585764  3.436175 0.002251967 0.01125984  0.0234086522 0.08557062