Virata manual

recode

Turns values into other values by rule — ages into age bands, say.

What we have

  • single values, ranges written with a slash, and else
  • generate() to keep the original

Coming later

  • recode's label options, which name the new categories as they are made

How you write it

recode var (rule = newvalue) [(rule = newvalue) ...] [, generate(newvar)]

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

What it does

recode age (0/14=1) (15/59=2) (else=3), generate(agegroup) reads as: nought to fourteen becomes 1, fifteen to fifty-nine becomes 2, everything else becomes 3. A rule can be a single value, a range written with a slash, or else.

The first rule that matches wins, so order them the way you would read them aloud. Use generate() to put the result in a new column and keep the original; without it the original is overwritten.

Try it

Every example below was run after sysuse vira.sample02, clear.

. recode age (0/14=1) (15/59=2) (else=3), generate(agegroup)
The same thing in pandas and in R

pandas

import numpy as np
import pandas as pd

values = pd.to_numeric(df["age"], errors="coerce")
tests = [values.between(0, 14), values.between(15, 59), values.notna() | values.isna()]
answers = [1.0, 2.0, 3.0]
df["agegroup"] = pd.Series(np.select(tests, answers, default=values), index=df.index)

R

# no R form for `recode` yet -- see docs/r-equivalents.md

Nearby

generate replace egen rename order drop