Virata manual

reshape

Swaps the data between wide and long shape.

What we have

  • reshape long and reshape wide, with i() and j()

Coming later

  • reshape error, which shows why a reshape will not go

How you write it

reshape long stub, i(idvar) j(newvar)   |   reshape wide stub, i(idvar) j(var)

Square brackets mean optional. A vertical bar means choose one.

What it does

Wide means one row per person with a column per year: income2004, income2006, income2008. Long means one row per person per year, with a year column and one income column.

Most analysis, and every chart in Virata, wants long. reshape long income, i(id) j(year) does the conversion; reshape wide goes back.

The two options are the whole command: i() is what identifies a person and stays constant, j() is the new column that will hold what used to be part of a column name.

Try it

. set language python
language is now python
(note: `set show` does not apply in Python mode -- a Python line is run as code, not parsed, so there is nothing to translate. It works in Stata and in R.)
. df = pd.DataFrame({'id': [1, 2], 'inc1': [5, 6], 'inc2': [7, 8]})
. set language stata
language is now stata
. reshape long inc, i(id) j(year)
Data  wide -> long
Number of observations   2  ->  4
j variable (2 values)          year
xij variables:  inc
The same thing in pandas and in R

pandas

import pandas as pd

df = pd.melt(df, id_vars=['id'], var_name="year", value_name="inc")
df["year"] = pd.to_numeric(df["year"].astype(str).str.removeprefix("inc"), errors="coerce")
df = df.sort_values(['id', 'year']).reset_index(drop=True)

R

library(tidyr)
df <- df %>% pivot_longer(starts_with("inc"), names_prefix = "inc",
    names_to = "year", values_to = "inc")

# This R has NOT been run against a real R yet: read it as documentation.

Nearby

merge append joinby cross collapse contract