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

Stata bysort: group, sort and generate variables

Use Stata bysort to separate group membership from row order, with a worked example covering counts, missing scores and previous observations.

Written and maintained by CASRAI Editorial Board

Published

On this page

Stata bysort sorts observations and repeats a command separately within each group: bysort groupvar: command. Put ordering variables in parentheses, as in bysort site (visit): generate sequence = _n, to number visits within sites without making every visit a separate group. The walkthrough below distinguishes group size from nonmissing counts and shows exactly which earlier observation a calculation uses.

What Stata bysort is used for in research

Researchers use the prefix to apply the same operation separately to study sites, participants, households or other groups represented in their data. The command after the colon determines the result: summarize prints descriptive statistics, egen can attach a group statistic to each observation, and generate can create an observation number or a value based on another row within the group.

The distinction matters when a dataset contains repeated observations. A site average and a visit sequence answer different questions, even though both involve grouping. The first needs the values belonging to a site; the second also needs an explicit order. Stata’s by manual documents both arrangements. Its Functions and expressions manual explains how observation numbers and subscripts change meaning inside groups.

For a table of means and other descriptive measures, the separate guide to descriptive statistics in Stata covers the reporting commands. Here the central task is controlling which rows a command treats together, which order it uses, and where the result ends up.

How to install or access Stata

Use StataCorp’s Stata installation guide for the download, installation and license setup. The guide provides Windows, Mac and Unix/Linux routes. It asks you to have your License and Activation Key ready and identify the MP, SE or BE edition specified by that key; retain an accompanying .stcodes file if one was supplied.

bysort is documented as a form of the official by prefix, rather than a separate contributed package. Once Stata is available, the examples below use documented commands directly. Start the illustrative exercise with an empty dataset, and save any current work before replacing data. Keep the commands together using a reproducible Stata do-file so that the input and the ordering choices remain visible together.

How to use Stata bysort step by step

Read the bysort Stata syntax

The basic pattern is bysort grouping_variables (ordering_variables): command. Variables outside the parentheses define the groups; those inside determine order within them. The colon separates the prefix from the operation. For example, grouping by site and ordering by visit differs from grouping by the combination of site visit.

  1. Enter a small example. These six observations are an illustrative composite, with fictional site, visit and score values. They are deliberately entered out of visit order, and one score is missing. In an empty dataset, enter the following block; end finishes data entry, and a period denotes a missing numeric value, as documented in Stata’s input manual.

    input site visit score
    1 3 18
    1 1 10
    1 2 14
    2 2 30
    2 1 20
    2 3 .
    end

    There are three visits per site. At site 1, all three scores are recorded. At site 2, the third visit exists but its score is missing. That difference lets you check whether a later count means rows or observed scores.

  2. Define the group and order, then number its rows. Run:

    bysort site (visit): generate sequence = _n

    The grouping variable is site. Within each site, ascending visit determines the order. The new sequence takes values 1, 2 and 3 separately at each site. Entering the data out of order makes the effect visible: site 1’s visit 1 receives sequence 1, although it was entered second.

  3. Record group size and the number of observed scores. Continue with:

    by site: generate n_rows = _N
    by site: egen n_scores = count(score)

    The first line records the number of rows in each site. The second uses the egen count function, which counts nonmissing values of its expression. Accordingly, both sites have n_rows = 3, while their n_scores values differ. Plain by works here because the previous command has already sorted by site, then visit.

  4. Attach a group mean. Run:

    by site: egen mean_score = mean(score)

    This adds the same site mean to each of that site’s rows. Site 1 has (10 + 14 + 18) / 3 = 14; site 2 has (20 + 30) / 2 = 25. The missing score is excluded from the mean calculation. The egen manual documents the group functions and their missing-value behavior.

  5. Reference the first or previous observation within each site. Re-establish the complete site/visit order before these order-dependent operations:

    bysort site (visit): generate first_score = score[1]
    by site: generate previous_score = score[_n-1]
    by site: generate change_score = score - score[_n-1]

    The first line copies the first ordered score within the site. The next two refer to the preceding observation within that same site. For its first visit, the subscript becomes zero, so the previous score is missing. The calculation never borrows the final observation from a different site.

  6. Inspect the generated columns and a printed summary. Run:

    list site visit score sequence n_rows n_scores mean_score previous_score change_score
    bysort site: summarize score

    list lets you inspect the row-level results. The final command prints a separate summary for each site, using the documented summarize command. It sorts only by site, so it does not preserve a specified visit order among ties on site. Before another previous-visit calculation, establish the site/visit order again.

Keep grouping variables outside parentheses

Compare bysort site (visit): generate a = _n with bysort site visit: generate b = _n. In the example, the first creates a three-row sequence per site. The second defines a separate group for each site/visit combination: because every combination occurs once, every value of b is 1. The commands differ by two parentheses, but the unit being counted changes completely.

When the research grouping really is a combination, put both identifiers outside parentheses. For instance, repeated observations nested within participants and sites would require both identifiers to define the group if participant codes are reused across sites. Choose the grouping variables from the dataset’s identifier structure, then state the within-group order separately.

How to read the output

bysort does not impose one universal output format. Interpret what the command after the colon produced. A generated variable appears in the dataset; a summary command prints a report. The expected values below are calculated from the fictional inputs above and the documented operations, rather than presented as a captured software session.

Site Visit Score Sequence Previous score Change score
1 1 10 1 Missing Missing
1 2 14 2 10 4
1 3 18 3 14 4
2 1 20 1 Missing Missing
2 2 30 2 20 10
2 3 Missing 3 30 Missing

Read across a row to check the ordering logic. The last row has a previous score of 30 even though its current score is missing; the difference is therefore missing. Read down each site to check that sequence restarts and that the first previous score is missing.

In the printed summarize output, Obs counts the nonmissing scores: three at site 1 and two at site 2. Mean is 14 and 25 respectively. The other default columns are standard deviation, minimum and maximum. Those summaries describe the observed scores; they do not tell you that a missing-score visit is absent from the dataset.

Adding mean_score keeps the visit rows available. If your intended output is instead a dataset with one summary row per group, see the Stata collapse guide. The downloadable data table below provides a separate crosswalk between grouping commands, their results and the relevant official references.

Troubleshooting Stata bysort

Resolve “not sorted” before interpreting results

Stata’s by manual demonstrates error r(5) when plain by encounters an unsuitable sort order. Use bysort site (visit): to establish the required order, or explicitly sort before using by site (visit):. If another command has reordered observations, re-establish the complete order before an order-dependent calculation.

Specify a meaningful order for tied observations

The sort manual states that observations tied on all sorting variables are randomized unless stable is specified. If two records share a site and visit, the expression “previous score” is ambiguous until another ordering variable resolves that tie. A sequence can run successfully while representing an unintended order.

Include a documented, meaningful secondary key inside the parentheses when the data supply one. Alternatively, sort site visit, stable followed by by site (visit): retains the previous relative order of ties. That preserves an existing order; it does not establish which of two tied records logically came first. The same manual notes that missing numeric sorting values follow nonmissing values, so inspect missing visit identifiers before treating the final row as the latest measured visit.

Separate row counts from nonmissing counts

_N counts rows in the by-group; egen count(score) counts its nonmissing scores. In the example, using three as site 2’s mean denominator would produce 50 / 3 instead of 25. Retain both counts when checking a grouped calculation so that a missing measurement remains distinguishable from a missing record.

Distinguish previous observations from time lags

score[_n-1] selects the preceding ordered row. If visit 2 is absent, the preceding record for visit 3 may be visit 1. Stata’s Functions and expressions manual recommends time-series operators for actual lags because they account for gaps. Define the time structure separately when a calculation requires the previous time period rather than the previous observed record.

Check command compatibility and stored results

Support for by is command-specific; even egen allows it only with certain functions. Its manual permits mean() and count(), but excludes it for rowmean(), which works across variables within a row. Read the selected function’s syntax instead of transferring a prefix to every operation.

Printed group results also differ from stored results. The by manual warns that only the last executed group’s stored results remain after a by run. Seeing several summary blocks does not mean later code can retrieve every group’s mean from one stored-result slot. Finally, rc0 continues to subsequent groups after an error; it does not fix the failed group’s calculation.

Free alternatives to Stata

The R Project describes R as free software for statistical computing. For grouped summaries, its official stats documentation supplies aggregate(). This covers the summary task, although a summary data frame has a different shape from the visit-level variables created in the walkthrough.

Alternative Documented grouped operation Result and source
R aggregate(score ~ site, data = visits, FUN = mean), where visits is an R data frame A summary data frame by site; see R stats: aggregate and the R Project’s software description.

The formula interface defaults to complete cases for the variables involved, and missing grouping values are omitted. Compare that sample definition with the Stata calculation before comparing results. The formula can use more than one grouping variable, but it does not express the parenthesized within-group ordering used by Stata’s prefix. Translate the intended output and missing-value rules as well as the grouping names.

Sources

Data: Stata grouped commands and result locations

Original compilation of documented Stata by, egen, summarize and within-group subscripting behavior. Recipes distinguish grouping variables, within-group ordering and result location; variable names match the illustrative walkthrough rather than an empirical dataset.

Stata grouped commands and result locations
TaskCommandGroup definitionWithin-group orderingResult locationOfficial reference
Number ordered rowsbysort site (visit): generate sequence = _nsiteAscending visitNew variable: sequenceby; Functions and expressions 13.7.2
Record group row countbysort site: generate n_rows = _NsiteUnspecified within siteNew variable: n_rowsFunctions and expressions 13.7.2
Count observed scoresbysort site: egen n_scores = count(score)siteUnspecified within siteNew variable: n_scores; nonmissing score countegen: count()
Attach group meanbysort site: egen mean_score = mean(score)siteUnspecified within siteNew variable: mean_score; site mean on each site rowegen: mean()
Print group summarybysort site: summarize scoresiteUnspecified within sitePrinted summary per site; stored results from last group onlysummarize; by technical note
Copy first ordered scorebysort site (visit): generate first_score = score[1]siteAscending visitNew variable: first_scoreFunctions and expressions 13.7.2

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 bysort: group, sort and generate variables

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 →