🤧 ggmice | 用这只可爱的小老鼠来填补你的缺失值吧!~

2022-11-10  本文已影响0人  生信漫卷

写在前面

我们在处理数据的时候常常会遇到存在缺失值(NA)的情况,如何处理就仁者见仁智者见智了。🤒
简单粗暴的方法可能就是行删除法(listwise)或者个案删除法(case-wise)了,这种方法在缺失值比较少的情况下比较适用,但在NA较多的情况下可能就会丢失过多信息导致无法继续分析。😘
本期我们介绍一下mice包ggmice包这两只可爱的小老鼠,全名Multivariate Imputation by Chained Equations, mice,即链式方程多重填补。📍

一张图总结基本原理,嘿嘿。👇

用到的包

rm(list = ls())
library(tidyverse)
library(mice) 
library(ggmice)

示例数据

这里我们使用一下示例数据airquality,再在其中添加一些缺失值

dat <- airquality
dat[4:9,3] <- rep(NA,6)
dat[1:4,4] <- NA

数据概览

4.1 缺失值查看

这里面我们一共有6个变量,其中4个存在缺失值。🫠

summary(dat)

4.2 缺失值可视化

Note! ggmice提供了一种NA值的可视化方法,一目了然,nice! 🤒

plot_pattern(dat,
             square = F,
             rotate = F)

4.3 influx-outflux plot

这里和大家简单介绍一下这个influx-outflux plot,总的来说评估了缺失数据其他变量联系程度。😂
一般来说,在建模时,influx以及outflux越大越好。😗

plot_flux(dat,
          label = F,
          caption = F)

可视化一下吧

5.1 连续变量

这里我们对连续变量缺失值进行一下可视化,可以看到红色的为缺失值。😘

ggmice(dat, aes(Ozone, Solar.R))+
  geom_point()

5.2 分类变量

接着我们对分类变量缺失值进行一下可视化,红色的为缺失值。😃

ggmice(dat, aes(Month, Solar.R)) +
  geom_point()

5.3 分面展示

ggmice(dat, aes(Month, Solar.R)) +
  geom_point() +
  facet_wrap(~ Month == 5,
             # labeller = label_both
             )

mice包填补缺失值

6.1 填补缺失值

在这里我们生成几个填补缺失值后的数据,m默认是5,为了减小计算量,这里我设置成3。🤗
Note! 可选method包括:👇

pmm,
logreg,
polyreg,
polr

imp <- mice(dat, m = 3, method = "pmm")

6.2 连续变量缺失值填补后可视化

我们再看一下填补缺失值后的散点图吧,红色的为缺失值填补后。😚

ggmice(imp, aes(Ozone, Solar.R))+
  geom_point()

6.3 分类变量缺失值填补后可视化

ggmice(imp, aes(Month, Solar.R)) +
  geom_point()

6.4 分面展示

ggmice(dat, aes(Month, Solar.R)) +
  geom_point() +
  facet_wrap(~ Month == 5,
             # labeller = label_both
             )

填补数据集的可视化

7.1 dotplot

我们之前设置了m = 3,这里我们看一下3个数据集的NA填补情况。🥰

ggmice(imp, aes(x = .imp, y = Temp)) +
  geom_jitter(height = 0, width = 0.25) +
  labs(x = "Imputation number")

7.2 boxplot

ggmice(imp, aes(x = .imp, y = Temp)) + 
  geom_jitter(height = 0, width = 0.25) +
  geom_boxplot(width = 0.5, size = 1, alpha = 0.75, outlier.shape = NA) +
  labs(x = "Imputation number")

算法收敛

看来default = 5是有原因的,哈哈哈哈哈哈!🤣

plot_trace(imp,
#           "Temp"
           )

<img src="https://img.haomeiwen.com/i24475539/a2d7dc19002b363b.png" alt="甜筒" style="zoom:25%;" />

<center>最后祝大家早日不卷!~</center>


点个在看吧各位~ ✐.ɴɪᴄᴇ ᴅᴀʏ 〰

<center> <b>📍 往期精彩 <b> </center>

📍 <font size=1>🤩 ComplexHeatmap | 颜狗写的高颜值热图代码!</font>
📍 <font size=1>🤥 ComplexHeatmap | 你的热图注释还挤在一起看不清吗!?</font>
📍 <font size=1>🤨 Google | 谷歌翻译崩了我们怎么办!?(附完美解决方案)</font>
📍 <font size=1>🤩 scRNA-seq | 吐血整理的单细胞入门教程</font>
📍 <font size=1>🤣 NetworkD3 | 让我们一起画个动态的桑基图吧~</font>
📍 <font size=1>🤩 RColorBrewer | 再多的配色也能轻松搞定!~</font>
📍 <font size=1>🧐 rms | 批量完成你的线性回归</font>
📍 <font size=1>🤩 CMplot | 完美复刻Nature上的曼哈顿图</font>
📍 <font size=1>🤠 Network | 高颜值动态网络可视化工具</font>
📍 <font size=1>🤗 boxjitter | 完美复刻Nature上的高颜值统计图</font>
📍 <font size=1>🤫 linkET | 完美解决ggcor安装失败方案(附教程)</font>
📍 <font size=1>......</font>

本文由mdnice多平台发布

上一篇 下一篇

猜你喜欢

热点阅读