为什么在使用R包鼠标进行插补期间显示错误消息?错误消息:$运算符对于原子向量无效

问题描述

我在R包鼠标中使用归插函数mice()处理包 VIM 中的 sleep 数据时遇到问题。错误消息是 $运算符对于原子向量无效。 睡眠数据的结构为:

> str(sleep)
'data.frame':   62 obs. of  10 variables:
 $ BodyWgt : num  6654 1 3.38 0.92 2547 ...
 $ BrainWgt: num  5712 6.6 44.5 5.7 4603 ...
 $ NonD    : num  NA 6.3 NA NA 2.1 9.1 15.8 5.2 10.9 8.3 ...
 $ Dream   : num  NA 2 NA NA 1.8 0.7 3.9 1 3.6 1.4 ...
 $ Sleep   : num  3.3 8.3 12.5 16.5 3.9 9.8 19.7 6.2 14.5 9.7 ...
 $ Span    : num  38.6 4.5 14 NA 69 27 19 30.4 28 50 ...
 $ Gest    : num  645 42 60 25 624 180 35 392 63 230 ...
 $ Pred    : int  3 3 1 5 3 4 1 4 1 1 ...
 $ Exp     : int  5 1 1 2 5 4 1 5 2 1 ...
 $ Danger  : int  3 3 1 3 4 4 1 4 1 1 ...

运行时显示错误

> mice(sleep)

 iter imp variable
  1   1  NonD  Dream  Sleep  Span  Gest
  1   2  NonD  Dream  Sleep  Span  Gest
  1   3  NonD  Dream  Sleep  Span  Gest
  1   4  NonD  Dream  Sleep  Span  Gest
  1   5  NonD  Dream  Sleep  Span  Gest
  2   1  NonD  Dream  Sleep  Span Error: $ operator is invalid for atomic vectors

我正在使用 R 4.0.2 mice_3.11.0 VIM_6.0.0

有人知道为什么会这样吗?非常感谢。

> sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

locale:
[1] LC_COLLATE=Chinese (Traditional)_Taiwan.950  LC_CTYPE=Chinese (Traditional)_Taiwan.950   
[3] LC_MONETARY=Chinese (Traditional)_Taiwan.950 LC_NUMERIC=C                                
[5] LC_TIME=Chinese (Traditional)_Taiwan.950    

attached base packages:
[1] grid      stats     graphics  Grdevices utils     datasets  methods   base     

other attached packages:
[1] mvtnorm_1.1-0    glmnet_4.0       Matrix_1.2-18    boot_1.3-25      mice_3.11.0      MASS_7.3-51.6   
[7] VIM_6.0.0        colorspace_1.4-1

loaded via a namespace (and not attached):
 [1] shape_1.4.4       zoo_1.8-8         tidyselect_1.1.0  purrr_0.3.4       haven_2.2.0       lattice_0.20-41  
 [7] carData_3.0-4     vctrs_0.3.0       generics_0.0.2    rlang_0.4.6       e1071_1.7-3       pillar_1.4.4     
[13] foreign_0.8-80    glue_1.4.1        sp_1.4-2          readxl_1.3.1      foreach_1.5.0     lifecycle_0.2.0  
[19] robustbase_0.93-6 cellranger_1.1.0  zip_2.0.4         codetools_0.2-16  laeken_0.5.1      rio_0.5.16       
[25] forcats_0.5.0     lmtest_0.9-37     curl_4.3          class_7.3-17      vcd_1.4-7         DEoptimR_1.0-8   
[31] broom_0.5.6       Rcpp_1.0.4.6      backports_1.1.6   abind_1.4-5       ranger_0.12.1     hms_0.5.3        
[37] stringi_1.4.6     openxlsx_4.1.5    dplyr_0.8.5       tools_4.0.2       magrittr_1.5      tibble_3.0.1     
[43] Crayon_1.3.4      car_3.0-8         tidyr_1.1.0       pkgconfig_2.0.3   ellipsis_0.3.1    data.table_1.12.8
[49] iterators_1.0.12  assertthat_0.2.1  R6_2.4.1          rpart_4.1-15      nnet_7.3-14       nlme_3.1-148     
[55] compiler_4.0.2   

解决方法

我想我找到了解决方案。在“mice”之后导入的任何其他库都会以某种方式与 mouse() 功能混淆。

一种解决方案是在您导入所有其他库(包括 tidyverse)后,最后导入重要的“鼠标”,然后最后导入鼠标。