模拟 (Y1, Y2) 上的数据,其中 Y2 具有缺失值

Simulating Data on (Y1, Y2) where Y2 has missing values

考虑一个二元变量(Y1, Y2)问题,每个变量定义如下:

我们如何在 (Y1, Y2) 上模拟大小为 500 的(完整)数据集?这是我在下面写的:

    n <- 500
    y <- rnorm(n)

我们如何模拟相应的观察数据集(通过强加缺失 在 Y2) 上?我不知道该问什么问题。

    n <- 500
    z1 <- rnorm(n)
    z2 <- rnorm(n)
    z3 <- rnorm(n)

    y1 <- 1 + z1
    y2 <- 5 + 2*z1 + z2

显示 Y2 的完整(最初模拟)和观测(施加缺失后)数据的边际分布。

您可能希望在数据模拟中包含一个误差项,因此方程中应包含另一个均值为零的向量,再次使用 rnorm(n)

seed <- sample(1:1e3, 1)

set.seed(635)  ## for sake of reproducibility

n <- 500
z1 <- rnorm(n)
z2 <- rnorm(n)

要获得缺失值,您可以对向量的一定百分比进行采样并将其设置为 NA

y2 <- 5 + 2*z1 + z2 + rnorm(n)  ## add error term independent of the `z`s

pct.mis <- .1  ## percentage missings
y2[sample(length(y2), length(y2)*pct.mis)] <- NA

## check 1: resulting missings
prop.table(table(is.na(y2)))
# FALSE  TRUE 
#   0.9   0.1 

summary(y2)
#   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
# -2.627   3.372   5.123   4.995   6.643  13.653      50

## check 2: rounded coefficients resemble equation
fit <- lm(y2 ~ z1 + z2)
round(fit$coe)
# (Intercept)          z1          z2 
#           5           2           1 

## check 3: number of fitted values equals number of non-missing obs.
length(fit$fitted.values) / length(y2)
# [1] 0.9

除了 @jay.sf 的精彩解释之外,另一种显示分布的方法是在新变量中构建缺失数据机制并比较两者 y2y2_missing:

library(ggplot2)
library(dplyr)
library(tidyr)
set.seed(123)
#Data
n <- 500
#Random vars
z1 <- rnorm(n)
z2 <- rnorm(n)
z3 <- rnorm(n)
#Design Y1 and Y2
y1 <- 1+z1
y2 = 5 + 2*(z1) + z2
#For missing
y2_missing <- y2
#Set missing
index <- which(((2*(y1-1))+z3)<0)
y2_missing[index]<-NA
#Complete dataset
df <- data.frame(y1,y2,y2_missing)
#Plot distributions
df %>% select(-y1) %>%
  pivot_longer(everything()) %>%
  ggplot(aes(x=value,fill=name))+
  geom_density(alpha=0.5)+
  ggtitle('Distribution for y2 and y2_missing')+
  labs(fill='Variable')+
  theme_bw()

输出: