Handle binary missing values with semi-automated marginalization
masterWhen working with binary (0/1) predictors that contain missing values (NA), Stan cannot sample the discrete parameters directly. map2stan handles this by performing semi-automated marginalization. It constructs a mixture model where the likelihood is the sum of the log-likelihoods conditional on all possible combinations of the missing 0/1 values.
To use this, specify a distribution for the binary variable (e.g., bernoulli(phi)) and ensure you provide constraints for the hyperparameters (e.g., phi must be between 0 and 1).
If you need to recover the unobserved values, set do_discrete_imputation=TRUE. This will compute the posterior probability of each missing value being 1.
# Example: Binary predictor with missingness
N <- 100
N_miss <- 10
x <- rbinom( N , size=1 , prob=0.5 )
y <- rnorm( N , 2*x , 1 )
x[ sample(1:N,size=N_miss) ] <- NA
f6 <- alist(
y ~ dnorm( mu , sigma ),
mu <- a + b*x,
x ~ bernoulli( phi ),
a ~ dnorm( 0 , 100 ),
b ~ dnorm( 0 , 10 ),
phi ~ beta( 1 , 1 ),
sigma ~ dcauchy(0,2)
)
# Use do_discrete_imputation=TRUE to get imputed probabilities
m6 <- map2stan( f6 , data=list(y=y,x=x) , constraints=list(phi="lower=0,upper=1") ,
do_discrete_imputation=TRUE )
precis( m6 , depth=2 )