---
title: "Introduction to fixes"
author: "Yosuke Abe"
date: "`r Sys.setlocale('LC_TIME', 'C'); format(Sys.Date(), '%B %d, %Y')`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to fixes}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## Introduction

The **fixes** package provides an easy-to-use toolkit for creating, estimating, and visualizing event study models using fixed effects regression. With **fixes**, you can automatically generate lead and lag dummy variables, flexibly estimate fixed effects event study regressions, and visualize the results with `ggplot2` using a single pipeline.

This vignette introduces the core functions of the package through simple examples, including recent updates such as multiple confidence interval support and improved plotting options.

## Installation

Install the released version from CRAN:

```r
install.packages("fixes")
```

Or with **pak** (recommended for fast install):

```r
pak::pak("fixes")
```

To install the latest development version from GitHub:

```r
pak::pak("yo5uke/fixes")
```

or

```r
devtools::install_github("yo5uke/fixes")
```

## Minimal Example

Below is a basic example simulating a panel dataset, running an event study, and visualizing the results.

```r
library(fixes)
library(dplyr)
library(tibble)

set.seed(2)

n_firms <- 1000
n_states <- 50
T <- 36

firm_id <- 1:n_firms
state_id <- sample(n_states, size = n_firms, replace = TRUE)
year <- 1980:2015

fe_firm <- rnorm(n_firms, mean = 0, sd = .5)
fe_year <- rnorm(T, mean = 0, sd = .5)
error <- rnorm(n_firms * T, mean = 0, sd = .5)

treated_1998 <- sample(c(1, 0), size = n_firms,
                       replace = TRUE, prob = c(1/2, 1/2))

df <- tibble(
  firm_id = rep(firm_id, each = T),
  state_id = rep(state_id, each = T),
  year = rep(year, times = n_firms),
  fe_firm = rep(fe_firm, each = T),
  fe_year = rep(fe_year, times = n_firms),
  error = error,
  is_treated = rep(treated_1998, each = T),
  after_treat = if_else(is_treated == 1 & year >= 1998, 1, 0),
  x1 = runif(n_firms * T),
  x2 = rnorm(n_firms * T),
  y = case_when(
    after_treat == 1 ~
      rnorm(n_firms * T, mean = .3, sd = .2) * (year - 1997) + fe_firm + fe_year + error,
    TRUE ~ fe_firm + fe_year + error
  )
)

# Run the event study (now supports multiple confidence levels)
event_study <- run_es(
  data       = df,
  outcome    = y,
  treatment  = is_treated,
  time       = year,
  timing     = 1998,
  lead_range = 18,
  lag_range  = 17,
  covariates = ~ x1 + x2,
  fe         = ~ firm_id + year,
  cluster    = ~ state_id,
  baseline   = -1,
  interval   = 1,
  conf.level = c(0.90, 0.95, 0.99) # Multiple CIs now supported!
)

# View results
head(event_study)
```

## Visualizing Event Study Results

The **fixes** package provides `plot_es()` for flexible visualization. You can easily switch between ribbon-style or error bar CIs, select the displayed CI level, and customize appearance.

```r
# Basic plot (default: ribbon, 95% CI)
p1 <- plot_es(event_study)
print(p1)

# Plot with error bars and 99% CI
p2 <- plot_es(event_study, type = "errorbar", ci_level = 0.99)
print(p2)

# Use a minimal theme and highlight the event period
p3 <- plot_es(event_study, type = "ribbon", vline_val = 0, theme_style = "minimal")
print(p3)

# Customize further with ggplot2
library(ggplot2)
p4 <- plot_es(event_study, type = "errorbar", ci_level = 0.9, theme_style = "classic") +
  scale_x_continuous(breaks = seq(-10, 10, by = 2)) +
  ggtitle("Event Study with 90% CI and Classic Theme")
print(p4)
```

## Handling Irregular Time Data

If your panel data uses irregular time variables (e.g., Dates), or has gaps, set `time_transform = TRUE` and provide a `unit` variable. This will replace the time variable with a consecutive sequence within each unit, ensuring leads/lags are calculated correctly.

### Example using `Date` and `time_transform`

```r
df_alt <- df |>
  mutate(date = as.Date(paste0(year, "-01-01")))

event_study_alt <- run_es(
  data           = df_alt,
  outcome        = y,
  treatment      = is_treated,
  time           = date,
  timing         = 19,        # 19th time point per unit (not the actual year!)
  lead_range     = 3,
  lag_range      = 3,
  fe             = ~ firm_id + year,
  cluster        = ~ state_id,
  baseline       = -1,
  time_transform = TRUE,
  unit           = firm_id
)

head(event_study_alt)
```

**Note:** When `time_transform = TRUE`, use the index (1, 2, 3, ...) for `timing` rather than the actual value (e.g., "1998-01-01"), and always specify `unit`.

## Package Highlights

- **`run_es()`**:
    - Fast, one-step event study for panel data.
    - Automatic creation of lead/lag dummies relative to treatment.
    - Supports both classic and staggered timing, covariates, clustering, weights, and flexible baseline normalization.
    - Multiple confidence interval levels supported (e.g., 90%, 95%, 99%).
    - Handles irregular time panels via `time_transform`.

- **`plot_es()`**:
    - Intuitive event study plot with ribbon or errorbar CI display.
    - CI level and visual style are fully customizable.
    - ggplot2-based for further modification.

## Conclusion

The **fixes** package streamlines event study estimation and visualization for panel data researchers. With a minimal API, multiple CI support, and robust visualization, it accelerates the workflow for dynamic treatment effect analysis.

For further details and full argument documentation, see:

```r
?run_es
?plot_es
```

Happy analyzing!🥂
