Written and maintained by CASRAI Editorial Board
Published
On this page
The egen command in Stata creates variables using extended functions, including group summaries, row means and combined identifiers. Use mean() or total() across observations, and rowmean() or rowtotal() across variables within an observation. The examples below show how missing values affect those results while retaining the original rows.
What egen in Stata is used for in research
Use egen when a derived variable needs information from several observations or several columns. A research analyst can attach each site’s mean measurement to its individual records, count available measurements within sites, or calculate a respondent’s mean across questionnaire items. StataCorp’s egen reference manual documents these functions and their individual rules.
The important choice is the direction of the calculation. A group mean looks down a measurement column across observations sharing a grouping value. A row mean looks across selected columns for one observation. Both create a new variable, but they answer different questions. Writing the intended unit beside the variable name helps prevent using a respondent-level score as though it were a site-level statistic.
Stata egen syntax and the difference from generate
egen newvar = function(arguments), options
Replace newvar with a new variable name and function with a documented egen function. The argument can be an expression or a variable list, depending on the function; options follow a comma. For example, egen site_mean = mean(x), by(site) calculates a mean within each site and places it on that site’s observations.
The generate and replace manual distinguishes creating a variable from changing an existing one. Use generate for an ordinary expression such as subtracting a group mean from a measurement. Use replace to change values after the variable exists. Egen functions are a separate function family; their names are not interchangeable with ordinary expression functions.
If the task is producing a report rather than storing derived variables, the descriptive statistics in Stata guide covers summary commands. If the intended result is a smaller dataset of group summaries, the collapse command guide explains that separate workflow.
How to install or access egen in Stata
Egen is documented as a Stata command in the Data Management Reference Manual. The functions used here require access to Stata rather than a separately installed community package. StataCorp’s installation guide provides the official download, installation and license-setup route.
For a new installation, have the License and Activation Key available and select the edition identified by that key. Follow the instructions for Windows, Mac or Unix/Linux on the official installation page. Within Stata, the documented menu route for egen is Data > Create or change data > Create new variable (extended).
For a repeatable analysis, keep the commands together with the input and scoring rules. The Stata do-file workflow provides a structure for recording those decisions. The walkthrough begins by clearing the data in memory, so save any work before running it in a fresh session.
How to use egen in Stata step by step
- Enter a small dataset with deliberate missing values.
This is an illustrative composite, using fictional records rather than study results. Each row has a site, a batch, three item responses and a measurement called x. A period represents a numeric missing value. The input syntax follows StataCorp’s input manual.
clear input site batch q1 q2 q3 x 1 1 2 4 6 10 1 1 4 . 8 14 1 2 . . . . 2 1 1 3 . 20 2 1 2 4 6 . 2 2 . . . . endThe fixture includes partially answered and entirely unanswered rows, plus measurements missing within both sites. Those cases let you check the denominator and the placement of results rather than inspecting only complete records.
- Calculate group means and nonmissing counts.
egen double site_mean = mean(x), by(site) egen n_x = count(x), by(site) generate double deviation = x - site_meanThe mean and count use nonmissing x values within each site. Site 1 has measurements 10 and 14, so its mean is (10 + 14) / 2 = 12 and its count is 2. Site 2 has only 20, so its mean is 20 and its count is 1. The group statistic appears even on a row whose own x is missing.
The deviation is a different calculation: each observation’s x minus its site’s mean. Site 1’s observed deviations are -2 and 2. Missing x remains missing in this subtraction. A group statistic being available does not mean the original measurement has been filled in.
- Calculate row means and record the available-item count.
egen double item_mean = rowmean(q1 q2 q3) egen n_answered = rownonmiss(q1 q2 q3) egen double item_total = rowtotal(q1 q2 q3), missingRowmean divides the sum of available responses by their number. For the second record, (4 + 8) / 2 = 6; it does not divide by three. Rownonmiss records that only two responses contributed. Rowtotal adds the available responses, and its missing option makes an entirely unanswered row missing instead of zero.
These row functions do not take a by prefix. The variables inside the parentheses already define what belongs to each calculation. Adding a site grouping would not turn three item columns into a different kind of row mean.
- Apply a stated minimum-response rule separately.
generate double score_min2 = item_mean replace score_min2 = . if n_answered == 0 | n_answered == 1For this fictional demonstration, suppose the analysis plan requires at least two answered items. The commands keep the unfiltered item_mean and create a separate score subject to that rule. This is an example rule, not a validated questionnaire scoring standard. Use the actual instrument’s scoring instructions for research data.
Egen’s ability to calculate an available-item mean does not decide whether the score should be used. Keeping n_answered alongside the score makes the computational denominator visible when checking an analysis against its scoring specification.
- Create identifiers and mark one row per group.
egen site_batch = group(site batch), label egen one_batch = tag(site batch) list site batch site_batch if one_batchGroup assigns integers to distinct site–batch combinations. It can combine numeric variables, strings or both. In this fixture there are four combinations, assigned codes 1 through 4 in the sort order of site and batch. The label option attaches value labels describing those combinations.
Tag instead produces a marker: one observation in each combination receives 1 and the others receive 0. The final list uses that marker to display one record per combination. The marker is useful for inspecting group-level values without displaying every repeated copy; it does not select a representative measurement statistically.
How to read the output
Egen’s main output is the new variable stored in the dataset. Inspect the input columns beside the derived values. A repeated group mean is expected: the same statistic has been attached to several records, rather than calculated separately from each record’s measurement.
list site x site_mean n_x deviation
list q1 q2 q3 item_mean n_answered item_total score_min2
The following expected values are calculated from the fictional fixture. They provide an arithmetic check on the row calculations; periods mean missing values.
| Record | Item mean | Answered items | Total with missing option | Score requiring two items |
|---|---|---|---|---|
| 1 | 4 | 3 | 12 | 4 |
| 2 | 6 | 2 | 12 | 6 |
| 3 | . | 0 | . | . |
| 4 | 2 | 2 | 4 | 2 |
| 5 | 4 | 3 | 12 | 4 |
| 6 | . | 0 | . | . |
For the group calculations, all three site 1 records carry site_mean = 12 and n_x = 2, including record 3. All three site 2 records carry site_mean = 20 and n_x = 1. Those counts refer to nonmissing x measurements, not the number of rows assigned to the site.
For a median stored in a variable, the same group-summary pattern uses median(). The median in Stata guide compares that task with commands that report a median directly. Here the focus is how a stored summary behaves alongside the original observations.
Troubleshooting egen in Stata
An entirely missing row becomes zero
That is rowtotal’s documented default. Add the missing option when an entirely missing row should remain missing. The option still sums available values on partially missing rows; it does not require every item to be present. Use an explicit response-count rule if complete responses are required.
A total differs from a running sum
egen total_x = total(x), by(site) attaches a site’s full total to its records. Stata’s ordinary sum() function under generate produces a running sum. StataCorp explicitly distinguishes the two in the egen manual. Choose the function according to whether the variable should hold a group total or an accumulating sequence.
Some records do not receive the group statistic
An if qualifier limits the observations participating in the command and receiving its result. For example, egen selected_mean = mean(x) if site == 1 leaves other sites missing in selected_mean. It does not calculate separate means for every site. Use by(site) for that task, and specify any sample restriction deliberately.
The destination variable already exists
Choose a new destination name for a new calculation. Generate also requires a new variable, while replace changes an existing one. For a transformation after an egen result, use a separate command, such as generate half_mean = site_mean / 2; the egen syntax calls a function rather than accepting an arbitrary expression after that function call.
Group codes or missing identifiers look unexpected
Group codes follow the sort order of the component values. Treat them as identifiers rather than ranks or meaningful quantities. Their numbering depends on the combinations present, so retain the source keys when combining independently prepared files.
By default, group returns missing when a component key is missing. Its missing option includes missing values as grouping values. Tag also offers a missing option for including missing keys. State whether a missing site or batch is meant to define a group before changing either command.
Free alternatives to egen in Stata
R is an alternative environment for these calculations. The R Project describes it as Free Software under the GNU General Public License. Its row functions and group functions cover comparable tasks, although their syntax and missing-value results differ.
| R route | Corresponding task | Behavior to check |
|---|---|---|
| Base R rowMeans and rowSums | Means or totals across numeric item columns | Missing values are retained by default; na.rm = TRUE omits them. |
| R stats ave | A group statistic returned at the original observation length | Grouping variables define subsets; FUN specifies the calculation. |
For a numeric data frame called items, rowMeans(items, na.rm = TRUE) uses the available entries. If every entry in a row is missing, it returns NaN; rowSums(items, na.rm = TRUE) returns zero for that case. The downloadable data table below compares these documented results with Stata’s defaults and missing option.
For a numeric vector x and a factor site, ave(x, site, FUN = function(z) mean(z, na.rm = TRUE)) calculates means within sites while returning a vector the same length as x. The official ave documentation defines this repeated group-result behavior. Check both the grouping keys and the missing-value policy when translating an analysis, rather than replacing function names mechanically.
Sources
- StataCorp: egen — Extensions to generate, checked 2026-11-17.
- StataCorp: generate — Create or change contents of variable, checked 2026-11-17.
- StataCorp: input — Enter data from keyboard, checked 2026-11-17.
- StataCorp: Stata installation guide, checked 2026-11-17.
- R Project: What is R?, checked 2026-11-17.
- R Core: Form Row and Column Sums and Means, checked 2026-11-17.
- R Core: Group Averages Over Level Combinations of Factors, checked 2026-11-17.
Data: Missing-value behavior of Stata and R row calculations
Original crosswalk compiled from StataCorp egen documentation and R Core row-sum and row-mean documentation. It compares available-item calculations and entirely missing rows for explicitly named options; no empirical study data are included.
| Function and option | Partially missing row | Entirely missing row | Documentation |
|---|---|---|---|
| Stata: rowmean(varlist) | Mean of nonmissing values | Missing (.) | StataCorp egen |
| Stata: rowtotal(varlist) | Sum treating missing values as zero | 0 | StataCorp egen |
| Stata: rowtotal(varlist), missing | Sum treating missing values as zero | Missing (.) | StataCorp egen |
| R: rowMeans(x, na.rm = TRUE) | Mean after omitting missing values | NaN | R Core colSums |
| R: rowSums(x, na.rm = TRUE) | Sum after omitting missing values | 0 | R Core colSums |
Sources
- StataCorp: egen — Extensions to generate (accessed 2026-11-17)
- R Core: Form Row and Column Sums and Means (accessed 2026-11-17)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







