Command reference

reshape — switch between wide and long data

Reorganize repeated measurements between columns and rows. In wide data, one row can contain math1 and math2; in long data, separate rows hold math for each term.

Syntax

reshape long stubs, i(idvars) j(indexvar) [string]
reshape wide stubs, i(idvars) j(indexvar) [string]

stubs are the shared variable-name parts, such as math and read in math1 math2 read1 read2. i() identifies the unit, such as a student. j() identifies the repeated measurement, such as term 1 or 2.

Directions and identifiers

long
Turn repeated columns into rows. reshape long math, i(id) j(term) combines math1 and math2 into math and creates term from their suffixes. The i() variables must uniquely identify the original wide rows.
wide
Turn repeated rows into columns named from the stub and index. Each combination of i() and j() must identify at most one observation. Variables not being reshaped must be constant within each unit.
i(varlist)
Specify one or more variables identifying a unit. For example, i(school student) uses the combination of school and student, while i(id) uses a single identifier.
j(variable)
Name the repeated-measurement index. It is created from column suffixes when reshaping long and read from the dataset when reshaping wide. Numeric suffixes are expected by default.
string
Use text index values, for example suffixes before and after, instead of numeric suffixes. The same option applies when the long-form index is a string variable.
@ in a stub
Mark where the index appears when it is not simply a suffix. For example, math@score matches names such as math1score and math2score.
reshape query; reshape error
reshape query shows the remembered reshape setup. After a failed reshape, reshape error shows available diagnostics, such as duplicated identifiers or variables that vary within a unit.

Example

The sample contains four students, a school name, and math and reading scores for two terms. It converts both subjects to long form and sorts the result by student and term.

clear
import delimited "data/student_scores_wide.csv"
reshape long math read, i(id) j(term)
sort id term
list
Open example in browser

Sample data included. Opens in a new tab; click Run.

What to look for

The result has eight observations: two terms for each of four students. The subject columns are now math and read, and term identifies the measurement. Student 1 has math scores 48 and 51 in terms 1 and 2; the school name repeats on both rows.