recode: map values and ranges into categories
Convert numeric values into a smaller set of categories while keeping the original measurement available for checking.
Independent software. Not affiliated with, sponsored by, or endorsed by StataCorp LLC.
Complete example
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
generate(math_band) creates a new variable instead of changing math. The three rules are inclusive at both ends.
Output from stats.camp
math_band | Freq. Percent Cum.
------------+-----------------------------------
1 | 4 16.67 16.67
2 | 10 41.67 58.33
3 | 10 41.67 100.00
------------+-----------------------------------
Total | 24 100.00
+-------------------------------+
| # id math math_band |
|-------------------------------|
| 1 1 45 1 |
| 2 2 51 2 |
| 3 3 43 1 |
| 4 4 56 2 |
| 5 5 48 1 |
| 6 6 60 3 |
| 7 7 57 2 |
| 8 8 61 3 |
+-------------------------------+
How to read the result
Four observations fall below 50, ten fall from 50 through 59, and ten are at least 60. The inline labels are attached to the generated value-label set, although this current frequency-table display shows the underlying codes.
Always check boundary values such as 49, 50, 59, and 60. Off-by-one rules are among the easiest recoding errors to overlook.
Common options and rules
generate(newvar)preserves the source;prefix(text)creates one prefixed output for every recoded variable.label(name)names the value-label set created from inline labels and requires a generated output.copyrestcarries values not selected by a qualifier into a generated variable; without it, out-of-scope rows are missing.testreports overlapping or unused rules.missing,nonmissing,min,max, and numeric ranges are supported rule components.
See the current recode entry and Stata's recode manual for an external reference.
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