---
title: "Example Design Declaration and Diagnosis for Preanalysis Plans"
subtitle: "In R"
output:
  html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(message = FALSE, warning = FALSE)
```

This document shows some things researchers may wish to add to their preanalysis plans using design declaration and diagnosis.  

# Setup

```{r}
library(DeclareDesign)
library(tidyverse)
library(texreg)
library(knitr)
set.seed(343)
```


# Declare the Design

```{r}
sample_size    <- 100
effect_size    <- 0.5
number_treated <- 50

two_arm_design <-
  
  # M: Model
  declare_model(
    N = sample_size, 
    U = rnorm(N),
    potential_outcomes(Y ~ effect_size * Z + U)
  ) +
  
  # I: Inquiry
  declare_inquiry(ATE = mean(Y_Z_1 - Y_Z_0)) +
  
  # D: Data Strategy
  declare_assignment(Z = complete_ra(N, m = number_treated)) +
  declare_measurement(Y = reveal_outcomes(Y ~ Z)) +
  
  # A: Answer Strategy
  declare_estimator(Y ~ Z, .method = lm_robust, estimand = "ATE")
```

\clearpage
# Mock Figure

```{r mock-figure}
one_run <- draw_data(two_arm_design)

one_run <-
  one_run %>%
  mutate(treatment = factor(Z, levels = 0:1, labels = c("Control", "Treatment")))

summary_df <- 
  one_run %>%
  group_by(treatment) %>%
  do(tidy(lm_robust(Y ~ 1, data = .))) %>%
  mutate(Y = estimate)

ggplot(summary_df, aes(treatment, Y)) +
  geom_point(size = 3) +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0) +
  geom_point(data = one_run, position = position_jitter(width = 0.1), alpha = 0.2) +
  theme_bw() +
  theme(axis.title.x = element_blank()) +
  ylab("Outcome") +
  ggtitle("Comparison of Control and Treatment Group Means", "Simulated Data")
```

\clearpage
# Mock Regression Table

```{r reg-table, results = "asis"}
fit <- lm_robust(Y ~ treatment, data = one_run)
htmlreg(
  fit,
  custom.coef.names = c("Intercept", "Treatment"),
  include.ci = FALSE,
  include.rmse = FALSE,
  include.adjrs = FALSE,
  stars = 0.05,
  custom.note = "%stars. HC2 robust standard errors are in parentheses.",
  caption = "Average Treatment Effect (Simulated Data)", 
  caption.above = TRUE,
  doctype = FALSE
)
```

# Diagnosis

```{r}
diagnosis <- diagnose_design(two_arm_design)
reshape_diagnosis(diagnosis, select = "Power") %>%
  kable()
```


