Skip to main content
v2026.11,610 entries · CC-BY 4.0

The reshape Command in Stata: Wide to Long and Back

How Stata’s reshape long and reshape wide commands convert data between wide and long layouts, the i() and j() options explained through a worked repeated-measures dataset, the stub-naming rules that cause most reshape errors, and when reshape fails versus when a different tool is the better choice.

Ask about The reshape Command in Stata: Wide to Long and Back

Answers are drawn from this guide and the rest of the CASRAI corpus, with a link to every source.

Answers are AI-generated from CASRAI’s own published pages and can be wrong, so check the linked sources before relying on one; your question is logged without personal data — never sold, never used to train a third-party model — to show us what CASRAI is missing, so please do not type personal or confidential details. How we use this

Written and maintained by CASRAI Editorial Board

Last updated

Stata’s reshape command converts a dataset between wide layout (one row per subject, with repeated measurements spread across separate columns like score1990 score1991 score1992) and long layout (one row per subject-per-time-point, with a single score column and a separate variable recording which time point each row belongs to). reshape long goes wide-to-long; reshape wide goes long-to-wide. Which layout you need depends on the command that comes next — xtset and most panel-data and repeated-measures commands require long, while some cross-tabulations and certain graphing commands expect wide.

This page covers the i() and j() options that every reshape command needs, a worked example using a three-timepoint repeated-measures dataset, the stub-naming rule that causes the large majority of real reshape errors, how to read those error messages, reshaping back from long to wide, and — per the angle of this guide — where reshape genuinely fails or becomes the wrong tool for the job, not just a syntax problem to work around.

Wide and long: the two layouts, and why the distinction matters

In wide format, each subject occupies exactly one row, and repeated measurements over time (or across conditions) live in separate columns — id score1990 score1991 score1992. In long format, each subject-timepoint combination occupies its own row — id year score, with three rows per subject instead of one. The two layouts contain the same information; they differ only in which dimension (subject, or subject-and-time) defines a row.

The choice is not stylistic. Stata’s panel-data and repeated-measures tooling — xtset, xtreg, mixed-model commands, most twoway time-series plots by group — expects long format, because it needs a time variable to operate on. Wide format is more natural for a codebook, for exporting a simple table, or for some cross-tabulations. Moving a dataset between the two is what reshape is for.

Basic syntax: reshape long, reshape wide, and the i() and j() options

reshape long stubnames, i(idvar) j(jvar)
reshape wide stubnames, i(idvar) j(jvar)

stubnames is the common stem shared by the repeated wide variables (score, if the wide variables are score1990 score1991 score1992). i(idvar) names the variable that uniquely identifies each subject — it must be unique per subject in wide format, and unique per subject-timepoint combination in long format. j(jvar) names the variable reshape creates (going long) or consumes (going wide) to record which timepoint each observation belongs to; its values come directly from the numeric or string suffixes on the wide variable names.

A worked example: a repeated-measures dataset

Consider a study that tested the same 200 participants at three timepoints, stored wide — one row per participant, one score column per wave:

. describe

Contains data
  obs:           200
  vars:             4
------------------------------------------
  id           long    %12.0g
  score1       byte    %8.0g
  score2       byte    %8.0g
  score3       byte    %8.0g
------------------------------------------

To analyse change over time — a repeated-measures ANOVA, a mixed model, or simply xtset id wave — this needs to become long, with one row per participant per wave:

. reshape long score, i(id) j(wave)
(note: j = 1 2 3)

Data                               wide   ->   long
-----------------------------------------------------------
Number of obs.                      200   ->     600
Number of variables.                  4   ->       3
j variable (3 values)                     ->   wave
xij variables:
             score1 score2 score3   ->   score
-----------------------------------------------------------

. describe

Contains data
  obs:           600
  vars:             3
------------------------------------------
  id           long    %12.0g
  wave         byte    %8.0g
  score        byte    %8.0g
------------------------------------------

reshape parsed the stub score off each wide variable name, took the remaining digit (1, 2, 3) as the values of the new wave variable, and stacked the three columns into one score column with three rows per id. Nothing about the underlying values changed — only the row/column layout did.

The stub-naming rule that causes most reshape errors

reshape identifies which wide variables belong together purely from their names: each must be the stub followed immediately by a suffix (score1, score2, score3, or equally score_1990, score_1991 — the underscore is fine, it just becomes part of the parsed suffix). What it cannot do is recognise that score1, test_wave2, and SCORE3 are conceptually the same repeated measurement under three different naming conventions — to reshape, those are three unrelated variables that happen to share no stub at all.

This is the single most common source of a failed or silently-wrong reshape: real datasets, especially ones assembled from multiple survey waves or merged from other software, rarely arrive with perfectly consistent stub names. If a rename pass is needed first (rename test_wave2 score2, or a loop over a list of inconsistent names), do it before calling reshapereshape has no option that infers a name mapping, it only ever parses the literal variable names it’s given.

The suffixes also have to be internally consistent in type: all numeric-looking, or all a matching string pattern. Mixing score1 with scoreFinal under the same stub fails, because Final is not a value j() can represent alongside 1, 2, 3 without the string option — and even with string, every stub used in the same command needs the same set of suffixes.

Reading reshape’s error messages

Three errors account for most real failures:

  • “variable <name> not found” / a stub variable simply isn’t recognised. Usually a stub-naming mismatch as above — run describe or ds score* first and confirm every variable you expect to be part of the stub actually matches the exact naming pattern.
  • “values of variable <idvar> not unique within <jvar>” (or the reverse, values not unique within i()). This means i() doesn’t actually identify one row per subject in wide format — there’s a duplicate id. Run duplicates report id (wide) or isid id wave (long, before reshaping wide) before reshaping, not after the error appears.
  • “<jvar> does not uniquely identify observations within <idvar>” when reshaping wide. The long dataset has more than one row for the same idwave combination — a duplicate or a botched prior reshape. reshape wide cannot decide which duplicate row’s value belongs in the single wide column, so it refuses rather than picking one silently.

All three are Stata refusing to guess at an ambiguous mapping rather than silently producing a wrong dataset — treat each as a genuine data problem to fix (rename, deduplicate, or re-check the identifier), not an obstacle to route around with a different option.

Reshaping back: long to wide

. reshape wide score, i(id) j(wave)
(note: j = 1 2 3)

Data                               long   ->   wide
-----------------------------------------------------------
Number of obs.                      600   ->     200
Number of variables.                  3   ->       4
j variable (3 values)              wave   ->   (dropped)
xij variables:
                             score   ->   score1 score2 score3
-----------------------------------------------------------

The i() and j() options are exactly the same going back — reshape stores enough information after a successful reshape to reverse it with reshape long / reshape wide alone (no options needed) once, but relying on that shortcut across a saved-and-reloaded dataset is fragile; writing i() and j() explicitly every time is the reliable habit. A round trip — wide to long and back to wide — reproduces the original layout exactly, provided nothing else changed the data in between.

When reshape fails vs. when you need a different tool

Not every wide/long problem belongs to reshape, and treating every failure as a syntax problem to force past is the wrong instinct in a few specific cases:

  • Genuinely inconsistent stub naming across many variable families. If several repeated-measure groups each use a different naming convention, the fix is a systematic rename pass (often scripted with foreach and a naming lookup) before reshaping — reshape itself has no fuzzy-matching option, and trying options like force (which exists for a narrower purpose, tolerating a partially unbalanced panel, not name mismatches) will not fix a naming problem.
  • Two independent time/classification dimensions at once — for example, scores that vary by both wave and test item. Current Stata versions do support more than one j() variable for this case, but the syntax and the resulting variable-naming rules get unwieldy quickly with more than two stub families; for anything beyond a simple two-dimensional case, it is often more maintainable to reshape one dimension at a time, or to do the transformation in a tool built around multi-dimensional pivots.
  • Very large or very wide panels. reshape builds the new layout entirely in memory before replacing the old one, which roughly doubles peak memory use during the operation. On datasets with many thousands of repeated-variable columns this can be slow or memory-constrained even when the syntax is entirely correct.
  • You only need to aggregate, not restructure. If the actual goal is one row per subject with a mean, sum, or count across the repeated measurements — not a full row-per-timepoint dataset — that is collapse, not reshape; reshaping to long purely as a detour to then collapse back to one row per subject is unnecessary work.
  • Outside Stata entirely. If a workflow already lives in Python or R, pandas’ melt()/pivot() and R’s tidyr::pivot_longer()/pivot_wider() solve the identical problem and may be the more natural fit if the rest of the pipeline is already in that language — there is no requirement to route a wide/long conversion through Stata just because the final analysis will run there.

A pre-reshape checklist

  1. Confirm the repeated wide variables share one exact stub naming pattern (ds stubname* or describe) — rename first if they don’t.
  2. Confirm i() is unique per row in the current layout: duplicates report id (wide) or isid id jvar (long).
  3. Note the current observation and variable counts before reshaping, so the reported before/after totals in the output confirm what you expect.
  4. Save the pre-reshape dataset under its own filename, or wrap the reshape in preserve/restore while testing — a bad reshape is easy to redo from a saved copy and awkward to reconstruct otherwise.
  5. After reshaping, spot-check row counts: long rows should equal wide rows multiplied by the number of timepoints (barring genuinely missing combinations).

Frequently asked questions

What do i() and j() actually mean in reshape?

i() names the variable that identifies the unit that stays one row in wide format — typically a subject or participant ID. j() names the variable that distinguishes the repeated observations — typically time, wave, or condition — and its values come from the numeric or string suffixes on the wide variable names.

Can I reshape more than one stub at once?

Yes. reshape long score income, i(id) j(wave) reshapes both score1 score2 score3 and income1 income2 income3 in a single command, as long as both stubs share the exact same set of suffixes.

Why does reshape say a variable isn’t j-variant, or fail to find my stub?

This is almost always the stub-naming rule above: the wide variables don’t share one exact stub-plus-suffix naming pattern that reshape can parse. Run describe or ds against the variable names you expect to be part of the stub and rename any that don’t match before reshaping.

Does reshape lose variable or value labels?

Labels on the stub variables themselves generally do not survive a reshape into a single combined variable in the way they were defined on each separate wide variable, since one label can no longer describe three formerly-distinct columns. Check label list and describe after reshaping rather than assuming labels carried over unchanged.

How do I undo a reshape I ran by mistake?

Reload the saved pre-reshape dataset with use ..., clear, or, if you wrapped the operation in preserve beforehand, run restore. reshape long/reshape wide run without options can also reverse the immediately preceding reshape in the same session, but a saved copy is the more reliable safety net.

Related reading

For the row-stacking and column-joining commands that solve a related but different data-management problem, see CASRAI’s guides on the append command in Stata and merging datasets in Stata. If the goal is aggregation rather than restructuring, see the collapse command in Stata. For the broader tidy-data principles that make a dataset easy to reshape in the first place, see tidy data rules for structuring research data. Choosing Stata over the alternatives in the first place is covered in the SPSS vs. Stata comparison and R vs. Stata comparison. For the broader landscape of tools covered here, see the Research Tools & Software hub.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →

Regulatory Radar

Stop finding out after the fact

$29/month, cancel anytime. Daily digest updates from our analysis, a dashboard holding the same items, and a cited assistant for everything they raise.

  • Federal Register, Federal Register+, Grants.gov, Regulations.gov, NSF News, UKRI, plus CASRAI’s own published content.
  • 44,322 indexed passages, and every answer cites the ones it drew on.