當(dāng)我們在數(shù)據(jù)集中缺少值時,重要的是考慮為什么它們會丟失以及它們對分析的影響。有時忽略丟失的數(shù)據(jù)會降低功耗,但更重要的是,有時它會使答案有偏差,并有可能誤導(dǎo)錯誤的結(jié)論。因此,重要的是要考慮丟失的數(shù)據(jù)機制是什么,以便對其進行處理。 Rubin(1976)區(qū)分了三種類型的誤報機制:
- 完全隨機缺失(MCAR)Missing completely at random:當(dāng)可以將缺少值的案件視為所有案件的隨機樣本時;在實踐中很少發(fā)生MCAR
- 隨機丟失(MAR)Missing at random :以我們擁有的所有數(shù)據(jù)為條件時,任何剩余的丟失都是完全隨機的;也就是說,它不依賴于某些缺少的變量。因此,可以使用觀察到的數(shù)據(jù)對缺失進行建模。然后,我們可以對可用數(shù)據(jù)使用專門的缺失數(shù)據(jù)分析方法,以糾正缺失的影響。
- 非隨機丟失(MNAR)Missing not at random:當(dāng)數(shù)據(jù)既不是MCAR也不是MAR時。這種情況通常很難處理,因為它將需要對缺失模式進行強有力的假設(shè)。
缺失數(shù)據(jù)的常見處理方法
- 人們嘗試處理丟失數(shù)據(jù)的一種常見方法是刪除所有缺少值的情況。這種方法稱為完整案例分析(CC:Complete cases)。但是,CC僅在數(shù)據(jù)為MCAR時有效。
- 另一種方法是多重插補(MI:multiple imputation),這是一種 (monte carlo) 蒙特卡洛方法,它模擬多個值以插補(填充)每個缺失值,然后分別分析每個插補數(shù)據(jù)集,最后將結(jié)果匯總在一起。我們多次估算缺失的數(shù)據(jù),以解決我們對缺失數(shù)據(jù)的真實(未知)值的不確定性。
- 在處理示例數(shù)據(jù)集時,我們對多重插補更加滿意。從理論上講,多重插補可以處理所有三種類型的缺失。但是,執(zhí)行多重插補通常不適合MNAR情況。MNAR類型的數(shù)據(jù)的數(shù)據(jù)分析更加復(fù)雜,這里我們假設(shè)數(shù)據(jù)是屬于 MAR 數(shù)據(jù)。
實際數(shù)據(jù)操作
# required libraries
library(mice)
## Warning: package 'mice' was built under R version 3.6.3
##
## Attaching package: 'mice'
## The following objects are masked from 'package:base':
##
## cbind, rbind
library(VIM)
## Warning: package 'VIM' was built under R version 3.6.3
## Loading required package: colorspace
## Loading required package: grid
## Loading required package: data.table
## VIM is ready to use.
## Since version 4.0.0 the GUI is in its own package VIMGUI.
##
## Please use the package to use the new (and old) GUI.
## Suggestions and bug-reports can be submitted at: https://github.com/alexkowa/VIM/issues
##
## Attaching package: 'VIM'
## The following object is masked from 'package:datasets':
##
## sleep
library(lattice)
載入數(shù)據(jù)
- 這是一個25行四列的數(shù)據(jù)
- A data frame with 25 observations on the following 4 variables.
- age:Age group (1=20-39, 2=40-59, 3=60+)
- bmi:Body mass index (kg/m**2)
- hyp:Hypertensive (1=no,2=yes)
- chl:Total serum cholesterol (mg/dL)
# load data
data(nhanes2)
dim(nhanes2)
## [1] 25 4
head(nhanes2)
## age bmi hyp chl
## 1 20-39 NA <NA> NA
## 2 40-59 22.7 no 187
## 3 20-39 NA no 187
## 4 60-99 NA <NA> NA
## 5 20-39 20.4 no 113
## 6 60-99 NA <NA> 184
md.pattern可視化缺失模式
md.pattern(nhanes2)
image.png
## age hyp bmi chl
## 13 1 1 1 1 0
## 3 1 1 1 0 1
## 1 1 1 0 1 1
## 1 1 0 0 1 2
## 7 1 0 0 0 3
## 0 8 9 10 27
VIM包對缺失數(shù)據(jù)可視化
- aggr函數(shù)可視化
library(VIM)
nhanes2_aggr = aggr(nhanes2,
col=mdc(1:2), # 顏色設(shè)置
numbers=TRUE,
sortVars=TRUE,
labels=names(nhanes2),
cex.axis=.7, gap=3,
ylab=c("Proportion of missingness","Missingness Pattern"))
image.png