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 reshape — reshape 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
describeords 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 meansi()doesn’t actually identify one row per subject in wide format — there’s a duplicateid. Runduplicates report id(wide) orisid 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
id–wavecombination — a duplicate or a botched prior reshape.reshape widecannot 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
renamepass (often scripted withforeachand a naming lookup) before reshaping —reshapeitself has no fuzzy-matching option, and trying options likeforce(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.
reshapebuilds 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, notreshape; 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’stidyr::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
- Confirm the repeated wide variables share one exact stub naming pattern (
ds stubname*ordescribe) — rename first if they don’t. - Confirm
i()is unique per row in the current layout:duplicates report id(wide) orisid id jvar(long). - Note the current observation and variable counts before reshaping, so the reported before/after totals in the output confirm what you expect.
- Save the pre-reshape dataset under its own filename, or wrap the reshape in
preserve/restorewhile testing — a bad reshape is easy to redo from a saved copy and awkward to reconstruct otherwise. - 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.








