Data Analysis Workflow
Run an end-to-end data analysis in R or Python: load, explore, analyze, and produce publication-ready output.
Input: $ARGUMENTS — a dataset path (e.g., data/county_panel.csv) or a description of the analysis goal (e.g., "regress wages on education with state fixed effects using CPS data").
Phase 0: Choose Language
Determine language from $ARGUMENTS or ask the user:
- User mentions
tidyverse, fixest, lm, .R context → R track
- User mentions
pandas, statsmodels, sklearn, .py or .ipynb context → Python track
- Dataset is
.csv/.parquet with no language cue → use AskUserQuestion with a single-select menu:
- header: "Language"
- question: "Which language should I use for this analysis?"
- options:
- label: "R (Recommended)", description: "tidyverse, fixest, ggplot2 — full plugin support with coding conventions and R reviewer"
- label: "Python", description: "pandas, statsmodels — supported for analysis scripts and figures"
- label: "Both", description: "R for figures and tables, Python for data processing"
R Track
Constraints
- Follow
rules/r-code-conventions.md for all standards
- Save scripts to
scripts/R/ with descriptive names
- Save all outputs (figures, tables, RDS) to
output/
- Use
saveRDS() for every computed object
- Run
r-reviewer on the generated script before presenting results
Phase 1: Setup and Data Loading
- Create R script with proper header (title, author, purpose, inputs, outputs)
- Load required packages at top (
library(), never require())
- Set seed once at top:
set.seed(42)
- Create output directories:
dir.create("output/analysis", recursive = TRUE, showWarnings = FALSE)
- Load and inspect the dataset
Phase 2: Exploratory Data Analysis
summary(), missingness rates, variable types
- Histograms for key continuous variables
- Scatter plots, correlation matrices
- Panel trends, pre-treatment comparisons if applicable
- Save all diagnostic figures to
output/diagnostics/
Phase 3: Main Analysis
- Panel data: use
fixest; cross-section: use lm/glm
- Cluster SEs at the appropriate level (document why)
- Multiple specifications: start simple, progressively add controls
- Report standardized effects alongside raw coefficients
Phase 4: Publication-Ready Output
Tables: modelsummary (preferred) or stargazer — export .tex and .html
Figures: ggplot2 with project theme; explicit ggsave(width = X, height = Y); save as .pdf and .png; add bg = "transparent" only if output is for Beamer slides
Phase 5: Save and Review
saveRDS() for all key objects
- Run the
r-reviewer agent: "Review the script at scripts/R/[script_name].R"
- Address Critical and High issues before presenting results
R Script Template
# ============================================================
# [Descriptive Title]
# Author: [from project context]
# Purpose: [What this script does]
# Inputs: [Data files]
# Outputs: [Figures, tables, RDS files]
# ============================================================
# 0. Setup ----
library(tidyverse)
library(fixest)
library(modelsummary)
set.seed(42)
dir.create("output/analysis", recursive = TRUE, showWarnings = FALSE)
# 1. Data Loading ----
# 2. Exploratory Analysis ----
# 3. Main Analysis ----
# 4. Tables and Figures ----
# 5. Export ----
Python Track
Constraints
- Save scripts to
scripts/python/ with descriptive names
- Save all outputs (figures, tables, pickles) to
output/
- Use
joblib.dump() for model objects; .to_parquet() for DataFrames
- Use
pathlib.Path for all file paths — never hardcode absolute paths
- Set random seeds at the top of the script
Phase 1: Setup and Data Loading
- Create Python script with header (title, author, purpose, inputs, outputs)
- Import all packages at the top of the file
- Set seeds:
np.random.seed(42) and random.seed(42)
- Create output directories:
Path("output/analysis").mkdir(parents=True, exist_ok=True)
- Load and inspect the dataset with
pandas
Phase 2: Exploratory Data Analysis
df.describe(), df.isnull().sum(), df.dtypes
- Histograms and distributions with
matplotlib/seaborn
- Scatter plots and correlation matrices
- Save diagnostic figures to
output/diagnostics/
- Save summary stats:
df.describe().to_csv("output/diagnostics/summary_stats.csv")
Phase 3: Main Analysis
- Cross-section OLS:
smf.ols("y ~ x", data=df).fit(cov_type="HC3")
- Panel data:
PanelOLS from linearmodels with cluster-robust SEs
- Multiple specifications: build incrementally
- Document SE choice with a comment
Phase 4: Publication-Ready Output
Tables: Format with pandas and export via .to_latex() or stargazer (Python port)
Figures: matplotlib/seaborn; explicit fig.savefig(path, dpi=300, bbox_inches="tight"); save as .pdf and .png
Phase 5: Save and Review
joblib.dump(model, "output/model.pkl") for fitted models
df_results.to_parquet("output/results.parquet") for DataFrames
- Review the script manually against the Python checklist below before presenting
Python Script Template
# ============================================================
# [Descriptive Title]
# Author: [from project context]
# Purpose: [What this script does]
# Inputs: [Data files]
# Outputs: [Figures, tables, pickle/parquet files]
# ============================================================
import random
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
import seaborn as sns
import joblib
from pathlib import Path
# Seeds
np.random.seed(42)
random.seed(42)
# Output directories
Path("output/analysis").mkdir(parents=True, exist_ok=True)
Path("output/figures").mkdir(parents=True, exist_ok=True)
# 1. Data Loading
# 2. Exploratory Analysis
# 3. Main Analysis
# 4. Tables and Figures
# 5. Export
Python Quality Checklist
[ ] All imports at top
[ ] Random seeds set (numpy + stdlib)
[ ] All paths use pathlib.Path — no hardcoded strings
[ ] Output directories created with mkdir(exist_ok=True)
[ ] Figures saved with explicit dpi=300, bbox_inches="tight"
[ ] Model objects saved with joblib.dump()
[ ] DataFrames saved as parquet
[ ] Comments explain WHY, not WHAT
Shared Principles
- Reproduce, don't guess. If the user specifies a regression, run exactly that.
- Show your work. Compute summary statistics before jumping to regression.
- Check for issues. Look for multicollinearity, outliers, perfect prediction, missing data.
- Use relative paths. All paths relative to repository root.
- No hardcoded values. Use variables for sample restrictions, date ranges, thresholds.
1---2name: data-analysis-23description: End-to-end data analysis workflow in R or Python — from exploration through regression to publication-ready tables and figures. Make sure to use this skill whenever the user wants to run any empirical analysis, write analysis code, or produce output from data. Triggers include: "analyze this data", "run a regression", "write R code for this", "write Python code for this", "I have a dataset", "help me with this regression", "run a DiD", "run an RDD", "event study", "IV regression", "fit a model", "produce a table", "make a figure", "explore my data", or any request involving a dataset path or empirical estimation.4---5
6# Data Analysis Workflow
7
8Run an end-to-end data analysis in R or Python: load, explore, analyze, and produce publication-ready output.
9
10**Input:** `$ARGUMENTS` — a dataset path (e.g., `data/county_panel.csv`) or a description of the analysis goal (e.g., "regress wages on education with state fixed effects using CPS data").
11
12---
13
14## Phase 0: Choose Language
15
16Determine language from `$ARGUMENTS` or ask the user:
17- User mentions `tidyverse`, `fixest`, `lm`, `.R` context → **R track**
18- User mentions `pandas`, `statsmodels`, `sklearn`, `.py` or `.ipynb` context → **Python track**
19- Dataset is `.csv`/`.parquet` with no language cue → use AskUserQuestion with a single-select menu:
20 - header: "Language"
21 - question: "Which language should I use for this analysis?"
22 - options:
23 - label: "R (Recommended)", description: "tidyverse, fixest, ggplot2 — full plugin support with coding conventions and R reviewer"
24 - label: "Python", description: "pandas, statsmodels — supported for analysis scripts and figures"
25 - label: "Both", description: "R for figures and tables, Python for data processing"
26
27---
28
29## R Track
30
31### Constraints
32- Follow `rules/r-code-conventions.md` for all standards
33- Save scripts to `scripts/R/` with descriptive names
34- Save all outputs (figures, tables, RDS) to `output/`
35- Use `saveRDS()` for every computed object
36- Run `r-reviewer` on the generated script before presenting results
37
38### Phase 1: Setup and Data Loading
391. Create R script with proper header (title, author, purpose, inputs, outputs)
402. Load required packages at top (`library()`, never `require()`)
413. Set seed once at top: `set.seed(42)`
424. Create output directories: `dir.create("output/analysis", recursive = TRUE, showWarnings = FALSE)`
435. Load and inspect the dataset
44
45### Phase 2: Exploratory Data Analysis
46- `summary()`, missingness rates, variable types
47- Histograms for key continuous variables
48- Scatter plots, correlation matrices
49- Panel trends, pre-treatment comparisons if applicable
50- Save all diagnostic figures to `output/diagnostics/`
51
52### Phase 3: Main Analysis
53- Panel data: use `fixest`; cross-section: use `lm`/`glm`
54- Cluster SEs at the appropriate level (document why)
55- Multiple specifications: start simple, progressively add controls
56- Report standardized effects alongside raw coefficients
57
58### Phase 4: Publication-Ready Output
59**Tables:** `modelsummary` (preferred) or `stargazer` — export `.tex` and `.html`
60**Figures:** `ggplot2` with project theme; explicit `ggsave(width = X, height = Y)`; save as `.pdf` and `.png`; add `bg = "transparent"` only if output is for Beamer slides
61
62### Phase 5: Save and Review
631. `saveRDS()` for all key objects
642. Run the `r-reviewer` agent: *"Review the script at scripts/R/[script_name].R"*
653. Address Critical and High issues before presenting results
66
67### R Script Template
68```r
69# ============================================================
70# [Descriptive Title]
71# Author: [from project context]
72# Purpose: [What this script does]
73# Inputs: [Data files]
74# Outputs: [Figures, tables, RDS files]
75# ============================================================
76
77# 0. Setup ----
78library(tidyverse)
79library(fixest)
80library(modelsummary)
81
82set.seed(42)
83dir.create("output/analysis", recursive = TRUE, showWarnings = FALSE)
84
85# 1. Data Loading ----
86# 2. Exploratory Analysis ----
87# 3. Main Analysis ----
88# 4. Tables and Figures ----
89# 5. Export ----
90```
91
92---
93
94## Python Track
95
96### Constraints
97- Save scripts to `scripts/python/` with descriptive names
98- Save all outputs (figures, tables, pickles) to `output/`
99- Use `joblib.dump()` for model objects; `.to_parquet()` for DataFrames
100- Use `pathlib.Path` for all file paths — never hardcode absolute paths
101- Set random seeds at the top of the script
102
103### Phase 1: Setup and Data Loading
1041. Create Python script with header (title, author, purpose, inputs, outputs)
1052. Import all packages at the top of the file
1063. Set seeds: `np.random.seed(42)` and `random.seed(42)`
1074. Create output directories: `Path("output/analysis").mkdir(parents=True, exist_ok=True)`
1085. Load and inspect the dataset with `pandas`
109
110### Phase 2: Exploratory Data Analysis
111- `df.describe()`, `df.isnull().sum()`, `df.dtypes`
112- Histograms and distributions with `matplotlib`/`seaborn`
113- Scatter plots and correlation matrices
114- Save diagnostic figures to `output/diagnostics/`
115- Save summary stats: `df.describe().to_csv("output/diagnostics/summary_stats.csv")`
116
117### Phase 3: Main Analysis
118- Cross-section OLS: `smf.ols("y ~ x", data=df).fit(cov_type="HC3")`
119- Panel data: `PanelOLS` from `linearmodels` with cluster-robust SEs
120- Multiple specifications: build incrementally
121- Document SE choice with a comment
122
123### Phase 4: Publication-Ready Output
124**Tables:** Format with `pandas` and export via `.to_latex()` or `stargazer` (Python port)
125**Figures:** `matplotlib`/`seaborn`; explicit `fig.savefig(path, dpi=300, bbox_inches="tight")`; save as `.pdf` and `.png`
126
127### Phase 5: Save and Review
1281. `joblib.dump(model, "output/model.pkl")` for fitted models
1292. `df_results.to_parquet("output/results.parquet")` for DataFrames
1303. Review the script manually against the Python checklist below before presenting
131
132### Python Script Template
133```python
134# ============================================================
135# [Descriptive Title]
136# Author: [from project context]
137# Purpose: [What this script does]
138# Inputs: [Data files]
139# Outputs: [Figures, tables, pickle/parquet files]
140# ============================================================
141
142import random
143import numpy as np
144import pandas as pd
145import statsmodels.formula.api as smf
146import matplotlib.pyplot as plt
147import seaborn as sns
148import joblib
149from pathlib import Path
150
151# Seeds
152np.random.seed(42)
153random.seed(42)
154
155# Output directories
156Path("output/analysis").mkdir(parents=True, exist_ok=True)
157Path("output/figures").mkdir(parents=True, exist_ok=True)
158
159# 1. Data Loading
160# 2. Exploratory Analysis
161# 3. Main Analysis
162# 4. Tables and Figures
163# 5. Export
164```
165
166### Python Quality Checklist
167```
168[ ] All imports at top
169[ ] Random seeds set (numpy + stdlib)
170[ ] All paths use pathlib.Path — no hardcoded strings
171[ ] Output directories created with mkdir(exist_ok=True)
172[ ] Figures saved with explicit dpi=300, bbox_inches="tight"
173[ ] Model objects saved with joblib.dump()
174[ ] DataFrames saved as parquet
175[ ] Comments explain WHY, not WHAT
176```
177
178---
179
180## Shared Principles
181
182- **Reproduce, don't guess.** If the user specifies a regression, run exactly that.
183- **Show your work.** Compute summary statistics before jumping to regression.
184- **Check for issues.** Look for multicollinearity, outliers, perfect prediction, missing data.
185- **Use relative paths.** All paths relative to repository root.
186- **No hardcoded values.** Use variables for sample restrictions, date ranges, thresholds.