Stata-to-R Translation Skill

SkillDev tools

Stata-to-R translation for data analysis. Maps Stata commands (reghdfe, xtreg, ivregress, margins, esttab, svy:) to R equivalents (fixest, plm, survey, marginaleffects, modelsummary). Use when user has Stata background or requests Stata-equivalent code comments in R pipelines.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the Stata-to-R Translation Skill skill

What this skill tells your AI

The instructions your AI receives, as published by daaf-contribution-community/daaf in .claude/skills/stata-r-translation/SKILL.md and read by ahel’s review.

Stata-to-R translation reference for quantitative social science data analysis. Maps Stata commands and packages (reghdfe, xtreg, ivregress, margins, esttab, svy:, graph twoway) to DAAF R equivalents (dplyr/tidyr, fixest, plm, survey, marginaleffects, modelsummary, ggplot2). Use when user mentions Stata background, requests Stata-equivalent code comments in R pipelines, needs to understand R analysis code from a Stata perspective, or wants to translate Stata data analysis concepts to R. Covers paradigm differences, command-by-command operation translations, regression modeling, causal inference, visualization, and workflow adaptation.

Cross-language translation reference for researchers moving between the Stata and R data analysis ecosystems. This skill maps Stata commands, idioms, and workflows to their DAAF R equivalents so that Stata-background users can audit, understand, and learn from DAAF-produced code, and so that code-producing agents can annotate their output with Stata equivalents when directed.

This skill is a routing hub -- it provides overview tables, decision trees, and directs readers to the detailed reference files listed below. The reference files contain the exhaustive command-by-command mappings, code examples, and edge-case documentation.

What This Skill Does

  • Maps the Stata command universe to DAAF's R stack across data management, regression modeling, causal inference, surveys, visualization, and workflow tooling
  • Provides a structured annotation protocol for agents to add inline Stata-equivalent comments to R code
  • Identifies paradigm gaps where Stata and R diverge fundamentally, so users know where to expect friction

Use cases:

  1. Stata user auditing DAAF R code and needing to understand what operations are being performed
  2. Agent annotating code with Stata-equivalent comments for a Stata-background researcher
  3. Stata user learning R for data analysis and needing a conceptual bridge
  4. Translating a specific Stata command or do-file idiom to its R equivalent
  5. Understanding where Stata commands have no direct R equivalent (and what the workaround is)

How to Use This Skill

Reference File Structure

Each topic in ./references/ contains focused documentation:

FilePurposeWhen to Read
paradigm-differences.mdCore language and paradigm differences (single-dataset model, missing values, value labels, macros, by:/_n/_N)Encountering fundamental Stata-vs-R confusion
data-management.mdgen/replace/keep/drop/sort/merge/append/reshape/collapse/egen to dplyr/tidyrReading or writing data manipulation code
strings-dates-labels.mdString functions, date epoch, value labels, encode/decode to stringr/lubridate/forcatsWorking with string, date, or categorical columns
regression-modeling.mdregress/areg/reghdfe/xtreg/ivregress/logit/probit/margins/test/esttab to fixest/stats/plm/marginaleffects/modelsummaryReading or writing regression code
causal-inference.mdDiD/RDD/IV/event studies/synthetic control/matching to fixest/rdrobust/did/MatchItWorking with causal inference methods
visualization.mdgraph twoway/bar/box/histogram to ggplot2/plotlyReading or writing visualization code
survey-spatial-ml.mdsvy: commands, spatial data, machine learning to survey/sf/tidymodelsWorking with surveys, spatial data, or ML
workflow-environment.mdDo-files/log/macros/ado/ssc to R/DAAF execution modelAdapting to DAAF's execution model
external-resources.mdCurated guides and tutorials with provenanceSeeking additional learning materials
gotchas.mdCommon Stata-user mistakes in RDebugging or reviewing code from Stata perspective

Reading Order

  1. Stata user auditing DAAF code: paradigm-differences.md then the relevant domain file (e.g., data-management.md for wrangling, regression-modeling.md for models) then gotchas.md
  2. Agent annotating code with Stata equivalents: Agent Code Annotation Protocol section below, then the relevant domain file for the code being annotated
  3. Learning R from Stata background: paradigm-differences.md then data-management.md then workflow-environment.md then external-resources.md
  4. Looking up a specific Stata command translation: Quick Decision Trees below, then the relevant reference file

Quick Decision Trees

"How do I do X from Stata in R?"

What kind of Stata command?
+-  Data management (gen, replace, keep, drop, merge, reshape, collapse)
|   +-- ./references/data-management.md
+-  Group operations (by:, bysort, egen)
|   +-- ./references/data-management.md
+-  Regression / estimation (regress, areg, reghdfe, xtreg, logit, probit)
|   +-- ./references/regression-modeling.md
+-  Post-estimation (margins, test, lincom, nlcom, predict, esttab)
|   +-- ./references/regression-modeling.md
+-  Causal inference (diff, did_multiplegt, rdrobust, teffects, synth)
|   +-- ./references/causal-inference.md
+-  Surveys (svyset, svy:)
|   +-- ./references/survey-spatial-ml.md
+-  Plotting (graph twoway, histogram, graph bar)
|   +-- ./references/visualization.md
+-  String/date manipulation (substr, strpos, date, mdy)
|   +-- ./references/strings-dates-labels.md
+-  Value labels (label define, encode, decode)
|   +-- ./references/strings-dates-labels.md
+-- Programming (local, global, foreach, forvalues, tempvar, preserve)
    +-- ./references/workflow-environment.md

"Why does this R code look different from Stata?"

What looks unfamiliar?
+-  Pipe operator (|> or %>%)
|   +-- ./references/paradigm-differences.md
+-  Missing values (NA vs .)
|   +-- ./references/paradigm-differences.md
+-  No single "dataset" -- multiple data frames everywhere
|   +-- ./references/paradigm-differences.md
+-  Value labels / factors
|   +-- ./references/paradigm-differences.md
+-  Formula interface (~) in model calls
|   +-- ./references/regression-modeling.md
+-  No `by:` prefix -- group_by() instead
|   +-- ./references/paradigm-differences.md
+-- library() calls and namespacing
    +-- ./references/gotchas.md

"I want to translate a Stata do-file to R"

What does the do-file do?
+-  Loads and wrangles data (use, gen, replace, keep, merge, collapse)
|   +-- ./references/data-management.md
+-  Runs regressions (regress, xtreg, reghdfe, ivregress)
|   +-- ./references/regression-modeling.md
+-  Creates tables (esttab, outreg2, margins)
|   +-- ./references/regression-modeling.md
+-  Creates plots (graph twoway, histogram)
|   +-- ./references/visualization.md
+-  Uses survey weights (svyset, svy:)
|   +-- ./references/survey-spatial-ml.md
+-  Multiple of the above
|   +-- Start with ./references/paradigm-differences.md, then each relevant file
+-- Uses macros, loops, or programs
    +-- ./references/workflow-environment.md

"Something isn't working and I think it's a Stata habit"

What went wrong?
+-  Missing values behaving differently than expected
|   +-- ./references/paradigm-differences.md
+-  gen/replace pattern not translating
|   +-- ./references/gotchas.md
+-  Merge producing wrong results
|   +-- ./references/gotchas.md
+-  Model output looks different from Stata
|   +-- ./references/regression-modeling.md
+-  Off-by-one error (0-indexed vs 1-indexed)
|   +-- ./references/gotchas.md
+-  `by:` / `_n` / `_N` not available
|   +-- ./references/paradigm-differences.md
+-- Macro syntax not working
    +-- ./references/gotchas.md

"Which R package replaces my Stata command?"

Which Stata command?
+-  regress / areg / reghdfe -> fixest
|   +-- ./references/regression-modeling.md
+-  xtreg (fe/re) -> fixest (FE) / plm (RE)
|   +-- ./references/regression-modeling.md
+-  ivregress / ivreg2 / ivreghdfe -> fixest (ivreg not pre-installed)
|   +-- ./references/regression-modeling.md
+-  logit / probit / ologit / mlogit -> stats::glm / MASS / nnet
|   +-- ./references/regression-modeling.md
+-  poisson / nbreg / ppmlhdfe -> fixest fepois / MASS::glm.nb
|   +-- ./references/regression-modeling.md
+-  margins / marginsplot -> marginaleffects
|   +-- ./references/regression-modeling.md
+-  esttab / outreg2 -> fixest etable / modelsummary
|   +-- ./references/regression-modeling.md
+-  test / lincom / nlcom -> car::linearHypothesis / marginaleffects hypotheses()
|   +-- ./references/regression-modeling.md
+-  gen / replace / drop / keep / sort -> dplyr
|   +-- ./references/data-management.md
+-  merge / append -> dplyr joins / bind_rows
|   +-- ./references/data-management.md
+-  collapse / egen -> dplyr summarise / mutate + group_by
|   +-- ./references/data-management.md
+-  reshape long/wide -> tidyr pivot_longer / pivot_wider
|   +-- ./references/data-management.md
+-  graph twoway / histogram / graph bar -> ggplot2
|   +-- ./references/visualization.md
+-  svyset / svy: -> survey package
|   +-- ./references/survey-spatial-ml.md
+-  rdrobust -> rdrobust (R, same authors)
|   +-- ./references/causal-inference.md
+-  binscatter -> binsreg (R, same authors)
|   +-- ./references/causal-inference.md
+-  synth -> augsynth / Synth (R)
|   +-- ./references/causal-inference.md
+-- ado-file / ssc install -> install.packages()
    +-- ./references/workflow-environment.md

Command Mapping Overview

Stata Command(s)R PackageFidelityKey Difference
regress, areg, reghdfefixestVery HighNear-identical formula syntax; | for FE absorption
xtreg, fefixestVery HighNo xtset needed; FE specified in formula
xtreg, replmHighRequires panel structure via pdata.frame or formula index
ivregress, ivreg2, ivreghdfefixest (ivreg not pre-installed)Very HighThree-part formula for IV in fixest; ivreg is not pre-installed and runtime installs are blocked (see Package availability note below)
logit, probit, ologit, mlogitstats::glm / MASS / nnetHighfamily = binomial for logit; separate packages for ordered/multinomial
poisson, ppmlhdfefixest fepois / stats::glmVery Highfepois for Poisson with multi-way FE
margins, marginsplotmarginaleffectsVery HighSame author as R version; near-identical API
esttab, outreg2fixest etable() / modelsummaryHighPublication-quality tables with flexible output formats
gen, replace, drop, keep, sortdplyrMediumVerb grammar (mutate, filter, select) vs imperative commands
merge, appenddplyr joins, bind_rowsHighNamed join types (left_join, inner_join) vs merge syntax
collapse, egendplyr summarise / mutate + group_byHighMust choose summarise (collapse) vs mutate (window)
reshape long/widetidyr pivot_longer / pivot_widerHighMore explicit column specification
graph twoway, histogram, graph barggplot2MediumGrammar of graphics vs imperative graph syntax
svyset, svy:surveyVery Highsvydesign() + svymean() etc.; mature, comprehensive
rdrobust, rdplotrdrobust (R)Very HighSame authors; identical API
binscatter, binsregbinsreg (R)Very HighSame authors; identical API
synthaugsynth / SynthHighMultiple implementations available
local, global, foreach, forvaluesR variables, for loopsLowFundamentally different paradigm (text substitution vs value binding)

Fidelity key: Very High = same authors, near-identical API. High = same capability, similar syntax. Medium = same capability, different API patterns. Low = fundamentally different paradigm requiring conceptual remapping.

Package availability: The core mappings above (fixest, plm, survey, marginaleffects, rdrobust, base stats, dplyr/tidyr, ggplot2) are pre-installed in DAAF. The specialized causal packages — ivreg, binsreg, augsynth, Synth, MatchIt, did, rddensity — are NOT pre-installed (for IV, pre-installed fixest three-part formulas or plm cover most cases), and runtime installs are blocked in DAAF (install.packages() is refused both at the command line and inside executed scripts — see CLAUDE.md § Runtime Package Installation). If one of these packages is genuinely required, escalate to the user to add it to the Dockerfile (user additions block) and rebuild before use.

Library Versions

Translations in this skill reference specific library versions. R versions are pinned in DAAF's Docker environment (R 4.5.3). Stata versions reference the current release as of May 2026. When syntax or behavior has changed between versions, the reference files note the change.

R PackageDAAF VersionStata EquivalentStata Version
dplyr + tidyr1.2.0, 1.3.2Data management commands (gen, replace, merge, etc.)Stata 18
fixest0.14.0regress, areg, reghdfe, ivreghdfe, ppmlhdfe, esttabStata 18 + reghdfe 6.x
stats (base R)4.5.xregress, logit, probit, glmStata 18
plm2.6-7xtregStata 18
systemfitnot pre-installedsuregStata 18
ggplot24.0.2graph twoway, graph bar, graph box, histogramStata 18
plotly (R)4.12.0(no direct Stata equivalent; interactive charts)N/A
survey4.5svyset, svy: prefix commandsStata 18
marginaleffects0.32.0margins, marginsplot, lincom, nlcomStata 18
rdrobust (R)3.0.0rdrobust, rdplot, rdbwselectrdrobust (SSC)
binsreg (R)not pre-installedbinsreg, binscatterbinsreg (SSC)
modelsummary2.6.0esttab, outreg2Stata 18
sandwich + lmtest3.1-1, 0.9-40robust, vce(robust), vce(hc3)Stata 18
MASS7.3-xnbreg, ologitStata 18
nnet7.3-xmlogitStata 18
car3.1-xtest, lincomStata 18
sf + terra1.1-0, 1.9-11spmap, spregressStata 18
tidymodels1.4.1(limited; teffects, psmatch2 partially)Stata 18

Stata version note: Stata 18 is the current release as of May 2026. Most command mappings apply to Stata 15+; version-specific features (frames, hdidregress) are noted in the reference files.

Top 10 Paradigm Differences

These are the friction points Stata users encounter most frequently when reading or writing DAAF R code. Each is covered in depth in the referenced file.

#Friction PointStata WayR WayReference
1Single-dataset modelOne dataset in memory; commands implicitMultiple data frames as variables; must specify whichparadigm-differences.md
2Missing values. = +infinity; 27 types (.a-.z)NA excluded from comparisons; one NA type per atomic typeparadigm-differences.md
3Value labelsThree-layer system (data, variable, value labels)factor() with levels and labels; ordering built-inparadigm-differences.md
4by:/_n/_N systembysort group: gen x = _Ngroup_by(group) |> mutate(x = n())paradigm-differences.md
5In-place modificationreplace var = expr modifies data directlydf <- df |> mutate(var = expr) creates new data frameparadigm-differences.md
6Macro system`local' and $global text substitutionR variables + paste0() / glue::glue()paradigm-differences.md
7Formula interfaceregress y x1 x2 (bare names, space-separated)lm(y ~ x1 + x2, data = df) (formula with ~ and +)regression-modeling.md
8Verb grammargen z = x * 2 (command-based)df |> mutate(z = x * 2) (pipe-based verbs)data-management.md
91-based indexing_n starts at 1; var[1] = first obsR also 1-based (unlike Python) -- less friction heregotchas.md
10Package modelssc install pkg then use immediatelylibrary(pkg) required at top of scriptgotchas.md

Agent Code Annotation Protocol

This section defines when and how code-producing agents add inline Stata-equivalent comments to DAAF R scripts.

When to Annotate

Annotations are added only when the orchestrator explicitly passes a Stata-background directive to the agent. This is not a default behavior.

Trigger conditions (orchestrator activates this when any apply):

  • User states they have a Stata background
  • User requests Stata-equivalent comments in code
  • User asks to understand R code from a Stata perspective

How the orchestrator passes the directive: The orchestrator adds the following to the agent prompt:

"User has Stata background. Load stata-r-translation skill. Add inline Stata-equivalent comments for non-trivial data operations."

Comment Format

# Stata: keep if enrollment > 500
df <- df |> filter(enrollment > 500)

# Stata: gen log_enroll = log(enrollment)
df <- df |> mutate(log_enroll = log(enrollment))

# Stata: bysort state: egen mean_score = mean(test_score)
df <- df |> group_by(state) |> mutate(mean_score = mean(test_score)) |> ungroup()

# Stata: reghdfe wage education experience, absorb(industry year) cluster(state)
fit <- feols(wage ~ education + experience | industry + year,
             data = df, vcov = ~state)

# Stata: drop if missing(income)
df <- df |> filter(!is.na(income))

# Stata: merge 1:1 school_id using "districts.dta", keep(3) nogen
df <- df |> inner_join(districts, by = "school_id")

What to Annotate

  • Annotate: Data wrangling (dplyr/tidyr operations), modeling calls (fixest, stats, plm), visualization layer construction (ggplot2, plotly), causal inference method calls, survey estimation calls
  • Do NOT annotate: library() calls, cat()/stopifnot() validation lines, file I/O boilerplate (arrow::read_parquet, arrow::write_parquet), config sections, section separator comments

Rules

  • One # Stata: comment per logical operation, placed on the line immediately above the R code
  • Keep annotations to a single line; abbreviate complex Stata command sequences if needed
  • Stata annotations are in addition to standard IAT comments (# INTENT:, # REASONING:, # ASSUMES:), not a replacement
  • Consumer agents: research-executor, code-reviewer, debugger, data-ingest

Related Skills

SkillRelationship
tidyverseR-side data wrangling -- detailed API reference for dplyr/tidyr (the gen/replace/merge/collapse equivalent)
fixestR-side fixed effects regression -- detailed API for the regress/reghdfe/ivregress equivalent
ggplot2R-side static visualization -- detailed API for the graph twoway equivalent
plotly-rR-side interactive visualization -- no direct Stata equivalent
r-statsR-side general modeling -- covers base R stats, sandwich, lmtest (logit, probit, glm equivalents)
plmR-side panel/IV models -- covers xtreg equivalents (plm has no SUR estimator; for sureg see systemfit in regression-modeling.md)
survey-rR-side survey analysis -- covers svyset and svy: prefix command equivalents
sf-terraR-side spatial data -- covers Stata spmap/spregress equivalents
tidymodelsR-side ML -- covers limited teffects/matching equivalents
quartoR-side notebooks -- replaces do-file + log workflow
stata-python-translationParallel skill for Stata-background users reading Python code
r-python-translationR-to-Python translation for R users moving to DAAF's Python stack

Note: Individual tool skills contain library-specific usage guidance (syntax, gotchas, performance). This skill provides the Stata-to-R conceptual bridge -- use both together when a Stata-background user is working with a specific library.

ML interpretation/fairness asymmetry (honest signal): Python's ML interpretation and fairness ecosystem is genuinely deeper (SHAP, fairlearn, and related tooling). The R-side equivalents (iml, DALEX, kernelshap, fairmodels) are installed and covered by the tidymodels skill's interpretation.md and fairness.md, so real R workflows exist for these tasks -- but for ML-heavy interpretation or fairness translation questions the Python direction carries more depth. For those, stata-python-translation (Stata-to-Python) may map to a richer target ecosystem than the R side offers.

Topic Index

Shortened here. Read the whole file on GitHub.

Signals

GitHub stars
235
Forks
34
Last commit
Sep 2026
Advanced
Catalog kind
skill
Gateway key
stata-r-translation
Source
github.com/daaf-contribution-community/daaf