Skip to main content
v2026.11,986 entries · CC-BY 4.0

Stata egenmore: Install and Use the Extended egen Functions

How to install egenmore from SSC, which extra egen functions it adds, how to run xtile, nvals, rsum2 and clsst, and when built-in egen is enough.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

egenmore is a community-contributed Stata package, maintained by Nicholas J. Cox of Durham University, that adds dozens of extra functions to Stata’s egen command. You install it once from the SSC Archive with ssc install egenmore, and afterwards you call its functions in exactly the same form as the built-in ones: egen newvar = fcn(arguments) [if] [in] [, options]. This guide maps the functions by the help file’s own themes, shows how to run the best-documented ones, explains what each produces, and lists what to check when a function does not behave as expected.

What egenmore is used for in research

Stata’s official egen (“extensions to generate”) creates a new variable from a function of existing variables, such as a group mean, a row total or a count of non-missing values. egenmore (“Extensions to generate (more extras)”) supplies functions that the official command does not include. The help file groups them under seven themes: grouping and graphing; strings, numbers and conversions; dates, times and time series; summaries and estimates; first and last; random numbers; and row operations.

In research work these functions mostly appear during data preparation, the step between raw data and the analysis file. Typical jobs are cutting a continuous measure into quantile groups within subgroups (xtile()), counting distinct values of an identifier or a set of columns (nvals(), rownvals()), summing survey items without turning an all-missing row into a false zero (rsum2()), assigning each observation the nearest of a set of reference values (clsst()), and tracking a running maximum within a person or unit over time (record()). Because these steps decide which observations enter a model, writing them as explicit commands in a do-file is also a reproducibility practice: the transformation is recorded, rerunnable and reviewable (see the CASRAI entry on results reproducibility).

The function families in the help file

The help file (egenmore.sthlp) lists each function with its syntax, its options and the Stata version it needs. The functions this guide covers, by theme, are:

  • Grouping and graphing: axis(), group2() and mlabvpos() build grouped or ordered variables for graph axes and marker-label positions; clsst() assigns the closest of a list of values.
  • Strings, numbers and conversions: noccur(), nss(), ntos(), nwords(), iso3166() and the base-conversion functions convert or count within strings and codes.
  • Dates, times and time series: dhms(), hms(), elap(), elap2(), eomd(), ewma(), filter() and filter7().
  • Summaries and estimates: nvals(), outside(), ridit(), xtile(), corr() and others.
  • First and last: first(), ifirst(), lastnm() and record().
  • Row operations: rowmedian(), rownvals(), rowsvals(), rsum2().

The help file is the authority on the complete list and on each option; run help egenmore after installing to see the version you have. The data table below compares the functions documented in this guide by the Stata version the help file states, the official counterpart it names, and the maintainer’s own remarks.

How to install or access egenmore

The package is distributed through the Statistical Software Components (SSC) Archive, also called the Boston College Archive and provided through RePEc. Stata’s own documentation calls SSC the premier download site for community-contributed Stata software. The RePEc record for the package (SSC identifier S386401) lists Nicholas J. Cox as author, a revision date of 24 January 2019, and the GNU General Public License version 3 as the terms of use. It also notes that Windows users should not try to download the files through a web browser, which is the reason to install from inside Stata.

  1. Inspect the package before installing it: ssc describe egenmore. This describes the package without installing it.
  2. Install it: ssc install egenmore. Stata’s ssc help states that installing loads everything associated with the package, including its help files. Add the replace option to overwrite an older copy, as in ssc install egenmore, replace.
  3. Read the documentation: help egenmore. You can also print the help file straight from the archive with ssc type egenmore.sthlp, which is how the RePEc record tells readers to reach the full details.
  4. Keep it current: Stata’s ado update command is the documented way to keep installed SSC packages up to date, and ssc uninstall egenmore removes the package.

Record the install in your project documentation. A do-file that uses egenmore functions will fail on a machine where the package is absent, so a project that others will rerun should say which packages it needs, and the plain line ssc install egenmore near the top of the do-file (or in a setup file) is the simplest way to say it. For a wider tour of finding other packages, see the CASRAI guide to Stata’s search command.

How to create variables with egenmore functions step by step

Every egenmore function uses the standard egen form: egen [type] newvar = fcn(arguments) [if] [in] [, options]. In the help file, by() is an option for many functions, and the help states that the by: construct may also be used with some of them. The steps are the same for every function; only the argument and the options change.

  1. Choose the function from the help file’s themes and confirm the Stata version it requires (each entry ends with, for example, “Stata 8.2 required”).
  2. Name the new variable and, if you want a particular storage type, put it before the name (egen byte flag = ...).
  3. Supply the arguments in the form the function expects: a variable, a variable list, a numlist or an expression.
  4. Add options and conditions after the comma, such as by(), missing or function-specific options.
  5. Inspect the result before using it (see the next section).

Quantile groups within subgroups: xtile()

xtile(varname) categorizes a variable by percentiles and works like Stata’s xtile command, with a by() option. Its options are percentiles(numlist) (abbreviated p()), nquantiles(#) (n()), weights(varname), altdef and by(byvarlist). By default the variable is dichotomized at the median. The help file’s two examples use the automobile dataset shipped with Stata:

egen mpg4  = xtile(mpg), by(foreign) p(25(25)75)
egen mpg10 = xtile(mpg), by(foreign) nq(10)

The first command builds quartile groups of mpg separately for domestic and foreign cars; the second builds deciles within each group. The help file notes that p(25(25)75) and n(4) both give quartiles.

Counting distinct values: nvals() and rownvals()

nvals(varname) returns the number of distinct values in varname, optionally within by() groups, ignoring missing values unless you specify missing. The help file’s remark is that the official tag() function followed by a sum can do much of the same job, and points readers to distinct and to the Stata Journal article “Speaking Stata: Distinct observations” (Cox and Longton 2008). rownvals(numvarlist) counts distinct values across several numeric variables within one observation: five variables with values 1, 1, 2, 2, 3 give 3. rowsvals() does the same for string variables.

Row sums that respect missing data: rsum2()

rsum2(varlist) generalizes the older rsum() function, which became rowtotal() in official Stata from Stata 9. Like rowtotal() it sums across variables and treats missing values as 0, but it adds two options. With allmiss, the sum is set to missing for any observation where all the variables are missing; with anymiss, it is set to missing for any observation where any variable is missing. For scale scores and indices this matters: without one of these options, a respondent who skipped every item receives a total of 0 and is indistinguishable from a respondent who scored 0.

Nearest reference value: clsst()

clsst(varname), values(numlist) returns whichever of the listed values is closest to the variable, disregarding sign. When a value is equally close to two listed values, the default is to report the earlier one, so with values(10 20) an observation of 15 gets 10; adding the later option reports 20. The help file’s example bins mpg to the nearest of 10, 15, …, 40:

egen mpgclass = clsst(mpg), v(10(5)40)

Running maximum within a unit: record()

record(exp) produces the maximum value observed “to date” of an expression, or the minimum with the min option. The order() option sets the sort order in which records are determined, and without by() or order() records follow the current order of the observations. The help file’s examples compute a worker’s highest and lowest earnings so far, separately for each person, in year order:

egen hiwage  = record(exp(lwage)), by(id) order(year)
egen lowage = record(exp(lwage)), by(id) order(year) min

Graph axes: axis()

axis(varlist) resembles group() but is designed for categorical graph axes: it creates a single variable with values 1, 2, … for the groups formed by the variables, in sort order, and the label() option attaches value labels or values. Its options include gap (adds a gap of 1 whenever a variable changes), missing and reverse. The help file’s example orders the categories of rep78 by the mean of mpg:

egen meanmpg = mean(-mpg), by(rep78)
egen Rep78   = axis(meanmpg rep78), label(rep78)
tabstat mpg, by(Rep78) s(min mean max)

Note the author’s own caveat in the same entry: he considers this approach superseded by his seqvar and labmask commands (Cox 2008, Stata Journal 8(2): 269-289). The related group2() function, which numbers groups by the result of another egen call such as group2(rep78) sort(mean(mpg)), is described in the help file as one where use of egroup() or axis() is now considered better style.

Strings and codes: noccur(), nss(), ntos(), iso3166()

noccur(strvar), string(substr) counts non-overlapping occurrences of a substring, so “aaaaa” contains two occurrences of “aa”. nss(strvar), find(substr) counts occurrences with an optional insensitive option; the help file itself says including both was an inadvertent duplication of identical functions by the maintainer. ntos() maps numeric values to strings from two matched lists, as in egen grade = ntos(Grade), from(1/5) to(Poor Fair Good "Very good" Excellent). iso3166() converts official short country names to ISO 3166-1 alpha-2 codes and back; it expects official names and returns missing for unofficial ones such as “Great Britain”, “Taiwan” or “Russia”, reporting by default only how many missing values it produced.

How to read the output

egen does not print a result table. A successful call silently adds one new variable, so the output you read is the variable itself. Check it with ordinary Stata commands before you use it:

  • describe newvar shows the storage type and label; summarize newvar shows the count, range and mean, which is enough to confirm that the number of non-missing observations is what you expect.
  • tabulate newvar works for categorical results such as xtile() groups, clsst() classes or rownvals() counts, and shows whether every category is populated.
  • list a few observations next to their source variables to confirm the logic row by row, especially for functions that depend on order (record(), first(), lastnm()), because the help file states these depend on the existing order of observations unless you sort or use order().

What each function returns, according to the help file: xtile() returns group numbers 1 upward (two groups at the median by default); nvals() and rownvals() return counts; rsum2() returns a number or missing depending on allmiss and anymiss; clsst() returns one of the values you listed; record() returns the running maximum or minimum; axis() returns group numbers 1, 2, … in sort order (reversed with reverse). Reporting the exact command, with its options, in your methods or replication documentation is more informative than the output, because the commands are what a reader needs to rerun the step. If you are summarizing the new variables afterwards, the CASRAI guide to descriptive statistics in Stata covers summarize, tabstat and codebook, and the guide on the collapse command covers building group-level summaries when you want a new dataset rather than a new column.

Troubleshooting egenmore

The function is not recognized

Stata reports an unknown egen function when the package is not installed on that computer. Run ssc install egenmore and repeat the command. If a function you saw in a tutorial is still not found, open help egenmore and check the exact spelling and the list of functions in the version you installed; the RePEc record notes that some of the routines are updates of those first published in the Stata Technical Bulletin (STB-50).

Your Stata version is too old for the function

Each entry in the help file states the Stata version it needs: clsst(), nvals(), record(), ntos() and rsum2() state Stata 6; noccur() and group2() Stata 7; corr() and outside() Stata 8; xtile() Stata 8.2; rownvals(), rowsvals() and rowmedian() Stata 9; and iso3166() version 9.2. Current Stata releases are far beyond these minimums, so this mainly affects projects run on very old installations.

An official function now does the same job

The help file warns about overlaps in several places. For rowmedian() it states that official Stata added a rowmedian() function in Stata 11 which always trumps the community one. For rsum() and rsum2() the official equivalent is rowtotal(), which in official egen accepts a missing option. For nmiss() the help file’s remark is that it is unnecessary, since egen nmiss = sum(missing(exp)) (or total() in Stata 9 and later) does the same. Before adopting an egenmore function, search the official egen help for an equivalent, because a built-in function is available to every colleague without an extra install.

Missing values and unexpected zeros

Row functions that treat missing values as zero produce a legitimate 0 for an empty row. Use the allmiss or anymiss options of rsum2(), or the missing option of rownvals() and nvals(), deliberately and state the choice in your documentation. For iso3166(), a count of missing values after a run usually means country names that are not the official short names; the help file describes an option that lists them so that you can correct the source variable.

The country list downloads from the internet

The help file states that iso3166() automatically downloads information from the ISO 3166 Maintenance Agency the first time it is used or when an update option is specified, and that updating the list can produce missing values when older do-files are run on datasets with countries that no longer exist, such as Yugoslavia. Pin the date of your country list in the do-file when you need the output to be identical across reruns.

Free alternatives to egenmore

Most of what egenmore does can be reached through official egen functions, other official commands or another community package. The table lists the alternatives that the documents read for this guide name explicitly; it is not a ranking.

Alternative What it covers Where it is documented
Official egen functions Built-in functions including anycount(), anymatch(), anyvalue(), concat(), count(), cut(), tag(), rowtotal() and rowmedian(), available without installing anything Stata help for egen
Official xtile and pctile commands Percentile and quantile categorization that egenmore‘s xtile() is modelled on (“works like” the command) egenmore help file; Stata help
distinct Counting distinct values, the alternative that the help file cites for nvals() Cox and Longton (2008), Stata Journal 8(4): 557-568
seqvar and labmask The commands the author names as superseding axis()-style ordering for graph axes Cox (2008), Stata Journal 8(2): 269-289
gtools gegen An efficient implementation of by-able egen functions written in C; its documentation says only egen functions or its own internally supported functions may be used with it gtools documentation, gegen page

When you switch to gegen, the gtools documentation says that for any function it does not implement internally it passes the call to a by-able egen function, so functions that egenmore supplies can still be called that way, provided they are by-able. For recoding a variable instead of creating a summary variable, the CASRAI guide to recoding variables in Stata covers the official routes, and the collected Stata code guide is a reference for do-file structure.

Sources

Data: egenmore functions: Stata version required and official counterpart

Compares fourteen egenmore functions by the Stata version the package help file states they need, the function or command the help file names as related or superseding, and the maintainer's remark. Compiled from the egenmore help file at the Boston College SSC Archive and the Stata egen help.

Period covered: Package revised 2019-01-24.

egenmore functions: Stata version required and official counterpart
FunctionStata version requiredWhat it returnsRelated, official or superseding item named in the help file
clsst()6The closest of a list of values to a numeric variableNone named
group2()7Group numbers ordered by the result of another egen callHelp file: egroup() or axis() is now considered better style
noccur()7Count of non-overlapping occurrences of a substringnss() duplicates it (help file: inadvertent)
nss()6Count of occurrences of a substring, optionally case-insensitivenoccur() duplicates it (help file: inadvertent)
nvals()6Number of distinct values, optionally by groupOfficial tag() plus a sum; distinct command
xtile()8.2Percentile-based category numbersWorks like the xtile command
outside()8Values more than factor() times the IQR from the nearer quartile, others missingDefault factor 1.5, as in a Stata box plot
corr()8Correlation of two variables, optionally covariance, Spearman or KendallNone named
rownvals()9Distinct values across numeric variables within an observationrowsvals() is the string version
rowsvals()9Distinct values across string variables within an observationrownvals() is the numeric version
rowmedian()9Row median across variablesOfficial rowmedian() since Stata 11 always trumps it
rsum2()6Row sum with allmiss and anymiss optionsGeneralizes rsum(), which became official rowtotal() from Stata 9
record()6Maximum (or minimum) so far of an expressionNone named
ntos()6String variable mapped from numeric valuesNone named

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Stata egenmore: Install and Use the Extended egen Functions

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →