【问题标题】:Extract multiply imputed datasets into a list of data frames将多重插补数据集提取到数据框列表中
【发布时间】:2021-09-11 02:42:14
【问题描述】:

我正在使用 mouse 包对我的数据执行多重插补,并希望将结果提取为数据框列表。这是我尝试过的,使用mapmice::complete

library(mice)

m = 2
data <- airquality[1:30,]
imp <- mice(data, seed = 123, m, print = F) #impute data
imp_list_df <- map(1:m, function(x) complete(imp, x))

我希望每个对象的类如下:

> class(imp_list_df)
[1] "list"
> class(imp_list_df[1])
[1] "data.frame"

目前class(imp_list_df[1]) 返回"list"。关于我可以使用函数而不是 map 来返回数据框列表的任何想法?

【问题讨论】:

    标签: r dataframe machine-learning iteration r-mice


    【解决方案1】:

    它是一个list 的data.frames。

    str(imp_list_df)
    List of 2
     $ :'data.frame':   30 obs. of  6 variables:
      ..$ Ozone  : int [1:30] 41 36 12 18 6 28 23 19 8 30 ...
      ..$ Solar.R: int [1:30] 190 118 149 313 8 313 299 99 19 194 ...
      ..$ Wind   : num [1:30] 7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
      ..$ Temp   : int [1:30] 67 72 74 62 56 66 65 59 61 69 ...
      ..$ Month  : int [1:30] 5 5 5 5 5 5 5 5 5 5 ...
      ..$ Day    : int [1:30] 1 2 3 4 5 6 7 8 9 10 ...
     $ :'data.frame':   30 obs. of  6 variables:
      ..$ Ozone  : int [1:30] 41 36 12 18 18 28 23 19 8 16 ...
      ..$ Solar.R: int [1:30] 190 118 149 313 66 307 299 99 19 194 ...
      ..$ Wind   : num [1:30] 7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
      ..$ Temp   : int [1:30] 67 72 74 62 56 66 65 59 61 69 ...
      ..$ Month  : int [1:30] 5 5 5 5 5 5 5 5 5 5 ...
      ..$ Day    : int [1:30] 1 2 3 4 5 6 7 8 9 10 ...
    

    提取list 的正确方法是使用[[

    class(imp_list_df[[1]])
    [1] "data.frame"
    

    当我们使用[进行提取时,它仍然返回list,即使用[1],它提取为length 1的list,并且元素是data.frame

    > str(imp_list_df[1])
    List of 1
     $ :'data.frame':   30 obs. of  6 variables:
      ..$ Ozone  : int [1:30] 41 36 12 18 6 28 23 19 8 30 ...
      ..$ Solar.R: int [1:30] 190 118 149 313 8 313 299 99 19 194 ...
      ..$ Wind   : num [1:30] 7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
      ..$ Temp   : int [1:30] 67 72 74 62 56 66 65 59 61 69 ...
      ..$ Month  : int [1:30] 5 5 5 5 5 5 5 5 5 5 ...
      ..$ Day    : int [1:30] 1 2 3 4 5 6 7 8 9 10 ...
    > str(imp_list_df[[1]])
    'data.frame':   30 obs. of  6 variables:
     $ Ozone  : int  41 36 12 18 6 28 23 19 8 30 ...
     $ Solar.R: int  190 118 149 313 8 313 299 99 19 194 ...
     $ Wind   : num  7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
     $ Temp   : int  67 72 74 62 56 66 65 59 61 69 ...
     $ Month  : int  5 5 5 5 5 5 5 5 5 5 ...
     $ Day    : int  1 2 3 4 5 6 7 8 9 10 ...
    

    另外,要一次检查每个元素的class,请使用sapply/lapply

    sapply(imp_list_df, class)
    [1] "data.frame" "data.frame"
    

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2021-11-27
      • 2012-03-29
      • 2018-04-08
      相关资源
      最近更新 更多