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

xtset in Stata: Declare Panel Data (Syntax, Errors)

How to declare panel data with xtset in Stata: syntax, time-unit options, delta(), reading the output and fixing r(451) errors.

Written and maintained by CASRAI Editorial Board

Published

On this page

xtset is the Stata command that declares the dataset in memory to be panel data: you name the variable that identifies each panel (the unit, such as a country, firm or patient) and, usually, the variable that records time. Stata’s own help states that you must run it before using the other xt commands, and that adding a time variable also sorts the data by panel and time and makes the time-series operators available. In the other word order, people search for stata xtset; it is the same command, typed as xtset panelvar timevar.

What xtset is used for in research

Researchers use xtset whenever the same units are observed repeatedly: countries across years, firms across quarters, participants across clinic visits, or airlines across periods. The command does not estimate anything. It records which variable identifies the unit and, optionally, which variable orders the observations, so that later commands (the xt estimators, and time-series operators such as lags and differences) know how the rows are related.

The two forms do different things. With only a panel variable, xtset panelvar declares the data to be panel data in which the order of observations is irrelevant, and Stata leaves the sort order unchanged. With a time variable, xtset panelvar timevar makes order relevant, sorts the data by panel and time, and lets you use the time-series operators and ts commands without a separate tsset call. If your question is which estimator to run once the data are declared, the CASRAI guide on panel data analysis with fixed and random effects covers that step; this page stops at setup.

Setup problems usually begin before xtset. Panel data are often delivered in wide form, with one column per year, and must be stacked into one row per unit and period first. The guide to the reshape command in Stata covers that conversion, and it should precede the xtset call.

How to install or access xtset

xtset is an official Stata command documented in Stata’s Longitudinal-Data/Panel-Data Reference Manual, so it is used from within an installed copy of Stata rather than added as a separate package. To read the current documentation from inside Stata, type help xtset. To reach it through the menus, choose Statistics > Longitudinal/panel data > Setup and utilities > Declare dataset to be panel data. The same dialog is the point-and-click route to everything described below.

Stata itself is commercial software from StataCorp, and access normally comes through an individual licence or an institutional one. If you work in a research group, ask the research office or IT service which licence applies to you. If you are new to writing do-files, the CASRAI guide to Stata code is a useful companion, because every xtset call should live in a do-file so that the declaration is repeated each time the analysis runs.

Stata’s help for xtset also names three practice datasets you can load with the webuse command: webuse pig, webuse airacc and webuse xtsetxmpl. They let you try each form of the command without preparing your own data.

How to declare panel data with xtset step by step

  1. Confirm the data are in long form. One row should represent one unit at one time. If each year is a separate column, reshape first.
  2. Check that both variables are numeric. The panel variable and the time variable must be numeric, and the time variable must hold integers. If the unit identifier is a string such as a country name, convert it first with egen cntry = group(country) or encode country, gen(cntry), as the help page shows, and then use the new variable.
  3. Check that each unit-time pair appears once. A panel requires each identifier and time combination to occur at most once. isid id time returns an error if the pair does not uniquely identify the rows; duplicates report id time counts the problem.
  4. Declare the panel. Type xtset panelvar timevar, for example xtset country year. In the dialog, the same step is Declare dataset to be panel data under Setup and utilities.
  5. Add a unit option if the time variable has no date format. If you have not yet assigned the appropriate %t format to the time variable, the unit options tell xtset the units: xtset country year, yearly, xtset company quarter, quarterly or xtset pid date, daily. For a daily date, you can instead give the variable a %td format first (format date %td) and then run xtset pid date. The data table below lists every unit option with its format and zero point.
  6. Add delta() when the spacing is not one unit. The default is delta(1). It is most often used with %tc clock-time variables, whose unit is the millisecond, where you can state the interval in seconds, minutes, hours, days or weeks, as in xtset pid tod, clocktime delta(1 hour). For other %t formats the units you can use in delta() are days or weeks. xtset checks that each panel follows the spacing and returns an error if the spacings are mixed.
  7. Re-display the settings whenever you need them. Typing xtset alone shows how the data are currently declared. xtset, clear removes the declaration; the help page calls it rarely used.

The data table below sets out each unit option with the %t format it applies and the value that corresponds to zero. Reading the unit option correctly matters because the same integer means different things in different formats: a yearly variable stores the calendar year itself, while a monthly variable counts months from 1960m1.

How to read the output

A successful call to xtset prints a short summary. For xtset country year, a Princeton University Library Stata guide shows this output:

Panel variable: country (strongly balanced) Time variable: year, 2011 to 2020         Delta: 1 unit

Each line answers a setup question:

  • Panel variable confirms which variable identifies the units. The note in brackets describes balance. Princeton’s guide explains strongly balanced as meaning every country has data for every year; the unbalanced case means some entities are not observed in some years.
  • Time variable confirms the time variable and its first and last values (here 2011 to 2020). If the range is not what you expect, a miscoded or mis-formatted time variable is the first suspect.
  • Delta shows the spacing between observations, 1 unit by default.

The summary is not only for reading. xtset leaves stored results that a do-file can test, so a script can stop when the data are not as expected. Stata’s help lists the scalars r(imin), r(imax), r(tmin), r(tmax), r(tdelta) and r(gaps), and the macros r(panelvar), r(timevar), r(tdeltas), r(tmins), r(tmaxs), r(tsfmt), r(unit), r(unit1) and r(balanced). With the noquery option, which suppresses the summary calculation and output, only r(tdelta), r(panelvar), r(timevar), r(tsfmt), r(unit) and r(unit1) are stored, so r(balanced) and r(gaps) are not available after a noquery call. A practical use is to follow xtset id year with a check on r(balanced) or r(gaps) before estimating anything, so a silent change in the input file shows up as a failed check rather than a changed result.

Once the panel is declared, time-series commands become relevant to it. For example, the CASRAI guide to the Dickey-Fuller test in Stata covers unit-root testing, which depends on the time structure that xtset or tsset records.

Troubleshooting xtset

Most xtset failures come from the data, not the command. The table summarises the errors that Stata’s own documentation and a university library guide describe, with the cause and the documented fix.

Message or symptom Cause Fix Source
string variables not allowed in varlist; The panel variable is a string, such as a country name Create a numeric version with encode country, gen(country1), then xtset country1 year; egen ... = group() is the alternative in the help page Princeton guide; Stata help
time variable must contain only integer values, r(451) The time variable has a fractional part. A %tc value counts milliseconds since 1 January 1960 00:00:00.000, and a date-time imported from Excel can carry a fraction of a millisecond Round it into a double and re-format: generate double TestTime2=round(TestTime,1) rounds to the nearest millisecond (round(x,1000) to the nearest second), then xtset PatientID TestTime2 Stata FAQ
repeated time values within panel, r(451) The same identifier and time combination occurs more than once; in the FAQ’s example, two cities had been given the same identifier Locate the collision with duplicates report id year, duplicates list id year or duplicates tag id year, gen(isdup); correct the source, such as giving one city a unique ID; drop the helper variable and re-run xtset Stata FAQ
Error when using delta() The values within a panel do not follow the stated spacing Check the spacing against the delta() you declared; xtset verifies it for every panel Stata help

The repeated-values case deserves the most care, because deleting duplicates to make the error disappear can discard real observations. The Stata FAQ’s advice is to find the source of the collision and correct it, as in its example where the identifier was changed for one of the two cities so each had a unique ID. Gaps, by contrast, are allowed: a panel with missing periods is unbalanced but still valid, and r(gaps) records whether any exist.

The related variant, xtset with no panelvar timevar, does not fix a data problem; it only reports current settings, so if an xt command complains that the data are not declared, run xtset with the variables again rather than typing it bare. A do-file that begins by loading the data, declaring the panel and checking r(balanced) will fail early and visibly, which is the behaviour you want in a replication package.

Free alternatives to xtset

Other tools do not have an xtset command, but they do the same job: tell the software which column is the unit and which is time. Each row below is sourced from that package’s own documentation.

Tool How the panel structure is declared Models documented Source
R, plm package An index argument on the estimation call, or pdata.frame(data, index = c("firm", "year")); by default the first two columns are taken as the individual and time indexes The model argument selects the estimator: "within" (the default, fixed effects) or "random" plm vignette on CRAN
Python, linearmodels A two-level index with the entity first and time second, as in data.set_index(['nr','year']) in the package’s example PooledOLS, BetweenOLS, FirstDifferenceOLS, RandomEffects and PanelOLS (fixed effects, with one or two effects) linearmodels panel documentation

The practical difference is that Stata stores the declaration in the dataset in memory, so later commands in the session read it, whereas in R and Python the declaration travels with the data object or the call. Cross-checking a Stata result against one of these tools is a common way to confirm that the panel was set up as intended, and a mismatch between the two setups, for instance a different time index, is easier to see when both are written in a script.

Whichever tool you use, record the panel and time variables, the unit option and any delta() value in the methods section or the code archive, so another researcher can reproduce the declaration exactly.

Sources

Data: xtset time-unit options in Stata: format and zero point

Compiled from Stata's help page for xtset: each unit option that tells xtset how to interpret the time variable, the %t display format it applies, and the value that corresponds to zero (or the example given). Reordered into one lookup table for choosing the option.

xtset time-unit options in Stata: format and zero point
xtset unit optionTime variable formatZero point or note
clocktime%tcMilliseconds from 1jan1960 00:00:00.000
daily%td0 = 1jan1960
weekly%tw0 = 1960w1
monthly%tm0 = 1960m1
quarterly%tq0 = 1960q1
halfyearly%th0 = 1960h1
yearly%ty1960 = 1960
generic%tgUnnamed generic units

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 · free to try

Ask about xtset in Stata: Declare Panel Data (Syntax, Errors)

2 free questions a day, no account.

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 →