*! version 1.1.0 01sep2025

Title

fencode -- Encode string or numeric variable into numeric codes ordered by frequency

Syntax

fencode
varname
[, generate(newvar) ascending]

Main
generate(newvar) name of new variable; default is varname_fencode

ascending order categories from least to most frequent; default is most to least frequent

Description

fencode provides frequency-based encoding of string and numeric variables.
Unlike encode which assigns codes alphabetically, fencode assigns
numeric codes ordered by frequency (descending or ascending). The command accepts
both string variables and labeled numeric variables with non-sequential codes,
standardizing them to sequential order. This functionality is particularly valuable
for creating tables and graphs where frequency ordering improves interpretability,
and for regression analysis where the most frequent category serves as a more
meaningful base category.

Options

Main

generate(newvar) specifies the name of the new encoded variable. If not specified,
the new variable is named varname_fencode where varname is the name of the
variable being encoded.

ascending orders categories from least frequent (code 1) to most frequent. The default
ordering is descending, with the most frequent category receiving code 1.

Examples

Basic usage demonstrating default behavior and options:

. webuse hbp2, clear

. fencode sex // Creates sex_fencode with default name

. fencode sex, gen(gender) // Same result with explicit name

. fencode sex, gen(gender_asc) ascending // Ascending order

Working with city temperature data:

. sysuse citytemp, clear

. fencode region

. graph bar (count), over(region_fencode) title("Cities by Region (automatically ordered by frequency)")

Standardizing arbitrary category codes:

. sysuse voter, clear

. fencode candidat // Converts codes 2,3,4 to clean 1,2,3

Using frequency ordering for regression base categories:

. webuse hbp2, clear

. fencode age_grp

. fencode sex

. logit hbp i.age_grp_fencode i.sex_fencode // Most frequent age group as base

Remarks

Stata's encode command provides essential functionality for converting string variables to
labeled numeric variables. However, it presents several limitations in practice. First, encode
assigns numeric codes alphabetically, which often conflicts with analytical needs where frequency
or logical ordering would be more appropriate. This limitation becomes particularly apparent when
using Stata's otherwise excellent table command, which lacks built-in sorting options. For instance, the command
table (varname), statistic(freq) statistic(percent) produces output in the order of the
underlying numeric codes, with no option to reorder by frequency or other criteria.

Second, encode requires explicit specification of the new variable name through the gen()
option, adding unnecessary verbosity for routine data processing tasks. Third, and perhaps most
limiting, encode only operates on string variables. Researchers frequently encounter labeled
numeric variables with non-sequential codes (e.g., 2, 7, 9) from survey instruments or legacy
systems that require standardization to sequential codes (1, 2, 3) for analysis or presentation.

fencode addresses these limitations by providing frequency-based encoding with sensible
defaults and broader applicability. The command encodes string variables into numeric codes
ordered by frequency, with the most frequent category receiving code 1 by default. It can also
re-encode existing labeled numeric variables, standardizing arbitrary numeric codes into clean
sequential series. The ascending option reverses the ordering when less frequent categories
should appear first.

This functionality proves particularly valuable in several contexts:

• Survey data analysis: Response categories with arbitrary codes (0=Never, 1=Sometimes,
7=Always) can be standardized to sequential codes ordered by prevalence

• Publication-ready tables: Frequency tables automatically display the most important
categories first without the need for manual sorting

• Panel data visualization: Entities (firms, countries, individuals) appear in graphs
ordered by their frequency in the dataset, improving interpretability

• Likert scale presentation: Response distributions in graphs and tables follow logical
frequency ordering rather than alphabetical ordering, particularly useful when using graphing
commands that lack straightforward sorting options

fencode maintains compatibility with encode's core behavior: missing values remain
missing, value labels are created automatically, and variable labels are preserved. The command
simply extends the encoding paradigm to support frequency-based ordering and numeric input variables,
while providing sensible defaults that reduce coding overhead.

Etymology: The command name fencode combines "f" for frequency with "encode",
directly indicating its purpose: frequency-based encoding.

Handling Special Cases:

Whitespace normalization: fencode automatically normalizes whitespace in string
variables, preventing categories with different spacing from being treated as distinct.
Leading, trailing, and multiple internal spaces are standardized.

Missing values: Following encode's behavior, missing values remain missing in the
encoded variable and are excluded from frequency calculations.

Frequency ties: When categories have identical frequencies, ties are broken alphabetically
for reproducible results.

Numeric input: If the input variable is numeric, it must have value labels attached.

Variable labels: The new variable inherits the label from the original variable.

Comparison with encode:

While encode assigns codes alphabetically, fencode assigns them by frequency.
This difference is particularly important for:

• Visualization: Graphs become more interpretable with categories ordered by prevalence

• Tables: Frequency tables show the most important categories prominently

• Analysis: Some procedures benefit from sequential coding starting at 1

• Data standardization: Non-sequential numeric codes are converted to sequential ones

The original data order is preserved. Only the new variable is created.

Author

Kabira Namit

World Bank

Email: knamit@worldbank.org

Acknowledgments

Thanks to Zoya Namit and Sofia Namit for playing somewhat independently and allowing their father to tinker away with Stata programs on a grey and cloudy Oxford weekend.