Command reference

recode — map numeric values into categories

Change numeric values according to a sequence of rules. Recode is useful for grouping scores into bands, combining category codes, or assigning a common code to selected values.

Syntax

recode varlist (oldvalues = newvalue) ... [if condition] [in first/last] [, options]

varlist is one or more numeric variables. Each parenthesized rule maps an individual value, a list, or an inclusive range to a new value. For example, (1 2 = 0) combines two codes and (50/59 = 2) maps every number from 50 through 59 to 2. A quoted label can follow the new value.

Options

generate(newvar ...)
Create new variables and keep the source variables unchanged. Supply one new name for each source variable. Without generate() or prefix(), recode changes the source variables.
prefix(text)
Create one new variable per source by adding the prefix to its name. For example, prefix(band_) creates band_math from math. Do not combine it with generate().
label(name)
Name the value-label set created from labels in the rules, such as (60/max = 3 "60 or more"). Use it with generate() or prefix(). Without an explicit label name, inline labels use the output variable’s name.
copyrest
When creating a new variable with if or in, copy original values for observations outside that selection. Without copyrest, those observations are missing in the new variable.
test
Report overlapping rules and rules that were never applied. The recode still changes the data; this option is a diagnostic, not a dry run.

Example

The sample groups math scores into three labeled bands while retaining math. It then counts the bands and lists the original score beside the new category.

clear
import delimited "data/student_scores.csv"
recode math (min/49 = 1 "Below 50") (50/59 = 2 "50 to 59") (60/max = 3 "60 or more"), generate(math_band) label(math_band_labels)
tabulate math_band
list id math math_band in 1/8
Open example in browser

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

What to look for

A math score below 50 receives code 1, a score from 50 through 59 receives code 2, and a score of 60 or above receives code 3. The labels make the frequency table readable; the stored category values remain numeric. Compare the listing with the rules to check the boundaries.