In Week 9, we learned how to conduct a simulation study. Is there a way we can simplify this code?
## set simulation parametersn <-100# sample sizepz <-0.2# probability of Z = 1alpha0 <-0# logit probability of x = 1 in non-smokers (z = 0)alpha1 <-1# log odds ratio of x = 1 in smokers (z = 1) vs non-smokersbeta0 <--3# logit probability of y = 1 in non-coffee drinkers (x = 0) and non-smokebeta1 <-0beta2 <-2simnum <-1000# number of iterations to run in the simulation# empty vectors to store the valuesunadj.p <- adj.p <-rep(NA, simnum)for(s in1:simnum){## generate confounder Z from a binomial distributionz <-rbinom(n, size =1, prob = pz)## compute probability of observing X = 1 from the inverse logit functionpx <-exp(alpha0 + alpha1 * z) / (1+exp(alpha0 + alpha1 * z))## randomly generate binary variable X from the above probabilityx <-rbinom(n, size =1, prob = px)## repeat above to randomly generate binary variable Ypy <-exp(beta0 + beta1 * x + beta2 * z) / (1+exp(beta0 + beta1 * x + beta2 * z))y <-rbinom(n, size =1, prob = py)## combine three random variables into a data framedat <-data.frame(lung = y, coffee = x, smoke = z)## fit unadjusted logistic regression modelunadj.mod <-glm(lung ~ coffee, data = dat, family ="binomial")unadj.coef <-summary(unadj.mod)$coef## fit adjusted logistic regression modeladj.mod <-glm(lung ~ coffee + smoke, data = dat, family ="binomial")adj.coef <-summary(adj.mod)$coef## save p-values for coffee from both models in a vectorunadj.p[s] <- unadj.coef[2,4]adj.p[s] <- adj.coef[2,4]## show simulation progressprint(s)}## calculate the type 1 error rate from each modelmean(ifelse(unadj.p <0.05, 1, 0))mean(ifelse(adj.p <0.05, 1, 0))
Motivation
Why should we try to simplify code?
Becomes easier to share and explain the code to others, promoting collaboration and reproducibility.
Reduces the chances of errors during coding.
Reduces debugging time.
Motivation
Let’s create a function to simplify this.
## set simulation parametersn <-100# sample sizepz <-0.2# probability of Z = 1alpha0 <-0# logit probability of x = 1 in non-smokers (z = 0)alpha1 <-1# log odds ratio of x = 1 in smokers (z = 1) vs non-smokersbeta0 <--3# logit probability of y = 1 in non-coffee drinkers (x = 0) and non-smokebeta1 <-0beta2 <-2simnum <-1000# number of iterations to run in the simulation# empty vectors to store the valuesunadj.p <- adj.p <-rep(NA, simnum)for(s in1:simnum){## generate confounder Z from a binomial distributionz <-rbinom(n, size =1, prob = pz)## compute probability of observing X = 1 from the inverse logit functionpx <-exp(alpha0 + alpha1 * z) / (1+exp(alpha0 + alpha1 * z))## randomly generate binary variable X from the above probabilityx <-rbinom(n, size =1, prob = px)## repeat above to randomly generate binary variable Ypy <-exp(beta0 + beta1 * x + beta2 * z) / (1+exp(beta0 + beta1 * x + beta2 * z))y <-rbinom(n, size =1, prob = py)## combine three random variables into a data framedat <-data.frame(lung = y, coffee = x, smoke = z)## fit unadjusted logistic regression modelunadj.mod <-glm(lung ~ coffee, data = dat, family ="binomial")unadj.coef <-summary(unadj.mod)$coef## fit adjusted logistic regression modeladj.mod <-glm(lung ~ coffee + smoke, data = dat, family ="binomial")adj.coef <-summary(adj.mod)$coef## save p-values for coffee from both models in a vectorunadj.p[s] <- unadj.coef[2,4]adj.p[s] <- adj.coef[2,4]## show simulation progressprint(s)}## calculate the type 1 error rate from each modelmean(ifelse(unadj.p <0.05, 1, 0))mean(ifelse(adj.p <0.05, 1, 0))
Overview
This function will return a data frame that has generated binary data from a logistic model.
sim_data <-binosim(n =10, px =0.4, baseprob =0.1, or =2)
Argument
Description
n
Sample size.
px
Probability of x.
baseprob
Baseline probability of Y.
or
True odds ratio.
Overview
This is how the function was created.
# Simulate binary data from simple logistic regressionbinosim <-function(n, px, baseprob, or) {# Generate predictor variable X from a binomial distribution x <-rbinom(n, size =1, prob = px)# Convert baseline probability to log-odds using the logit function baseprob <-log((baseprob) / (1- baseprob))# Calculate the log-odds using baseline probability as the intercept logodds <- baseprob +log(or) * x# Calculate the probability of success for Y given the log-odds py <-exp(logodds) / (1+exp(logodds))# Generate outcome variable Y from a binomial distribution y <-rbinom(n, size =1, prob = py)# Combine X and Y variables into a data frame sim_data <-data.frame(y = y, x = x)# Return the simulated datareturn(sim_data)}
Example
Let’s conduct a simulation study using binosim.
set.seed(123)true_or <-2simnum <-1000est <- se <- p_value <- or <- lower_ci <- upper_ci <- in_ci <-rep(NA,simnum)for (s in1:simnum){ sim_data <-binosim(1000, 0.5, 0.1, 2) mod <-glm(y ~ x, data = sim_data, family ="binomial") coef <-summary(mod)$coef est[s] <- coef[2,1] se[s] <- coef[2,2] p_value[s] <- coef[2,4] or[s] <-exp(coef[2,1]) lower_ci[s] <-exp(confint(mod)[2,1]) upper_ci[s] <-exp(confint(mod)[2,2])# Check if the true odds ratio is within the confidence interval in_ci[s] <- true_or >= lower_ci[s] & true_or <= upper_ci[s]}
Example
# Calculate empirical coveragemean(in_ci)
[1] 0.943
The simulated confidence intervals covered the true odds ratio approximately 94.3% of the time.
Example
Conclusion and Future Steps
This package creates an efficient way to generate binary data from a logistic model.
The generated data can be used for conducting simulation studies.
Future work will look into adding a confounder Z into the function.