reshape: convert wide data to long
Turn repeated measurements stored in separate columns into repeated rows identified by a new within-unit variable.
Independent software. Not affiliated with, sponsored by, or endorsed by StataCorp LLC.
Dataset and complete example
The synthetic wide dataset has one row per student and two measurements each for math and reading.
clear
import delimited "data/student_scores_wide.csv"
reshape long math read, i(id) j(term)
sort id term
list
math and read are stub names matching columns such as math1, math2, read1, and read2.
Reshape output from stats.camp
(j = 1 2)
Data wide -> long
-----------------------------------------------------
Number of obs. 4 -> 8
Number of variables 6 -> 5
j variable (2 values) -> term
xij variables:
math1 math2 -> math
read1 read2 -> read
+------------------------------------------+
| # id term math read school |
|------------------------------------------|
| 1 1 1 48 50 North |
| 2 1 2 51 54 North |
| 3 2 1 55 57 North |
| 4 2 2 59 60 North |
| 5 3 1 62 60 East |
| 6 3 2 65 66 East |
| 7 4 1 58 56 South |
| 8 4 2 61 63 South |
+------------------------------------------+
How i(), j(), and stubs work
i(id) identifies the logical unit and must uniquely identify rows in the wide data. j(term) names the new within-student index. The suffixes 1 and 2 become values of term, while each stub becomes one long measurement column.
school is not named in the command because it is constant within each ID and can be carried into both long rows.
Common options and failure checks
reshape longconverts matching wide columns to rows;reshape widereverses a properly identified long layout.i()can contain multiple identifier variables when one column is not sufficient.- Use the
stringoption when thej()suffixes are strings rather than integers. - The
@placeholder handles patterns where the varying suffix is not at the end of a name. - Duplicate
i()/j()combinations and variables that unexpectedly change withini()should be repaired, not suppressed.
stats.camp supports both directions plus common and advanced reshape syntax, but consequential conversions should still be checked for row counts, keys, labels, and missing combinations. See the current reshape entry and Stata's reshape manual.
Related guides
Run this exact example
Clone the example repository in stats.camp and open the exact do-file shown on this page. No stats.camp account is required.
Open this example