Stata for beginners: a practical guide to analysing data reproducibly

When you first open Stata, it is tempting to think you must learn a long list of commands before you can do anything useful. A better starting point is much simpler: understand what each row represents, check that the variables make sense, and save the steps that lead to an answer. A small, well-organised analysis that you can repeat tomorrow is worth more than a screen full of results you can no longer explain.

This guide follows that journey through a learning example and everyday tasks: importing Excel, finding missing values, preparing a graph, interpreting a regression, and handing over an organised project. It also uses two examples from the Licendi catalogue, Stata 18.0 and Stata 19.0, to connect the work you need to do with the version and edition you buy. Rather than another comparison of new features, this is a guide to building a reliable working method.

What Stata does and where it fits

Stata combines data management, statistical analysis, and graphics in one environment. You can use it to explore a survey, prepare academic research, analyse economic observations, or examine an organisation's indicators. Its practical appeal is not just that it calculates averages or fits models. It lets you connect preparation, analysis, and presentation without relying on a succession of manual changes that become difficult to remember.

Imagine receiving a new responses file every month. If you correct names, select participants, and calculate results manually, you must remember those decisions when the next file arrives. Writing the process as instructions makes it easier to repeat and to identify what changed. Automation does not guarantee a correct analysis, but it does make the decisions visible and easier for someone else to review.

You do not have to abandon spreadsheets. Excel can remain the place where someone collects information, while Stata validates and analyses it. The important part is agreeing on a stable input structure. Avoid mixing separate tables, subtotals, merged cells, and explanatory notes among the records in the same worksheet.

Write the question before opening the file

“I want to analyse the data” is not yet a working question. “I want to describe how monthly expenditure differs between household groups” already identifies an outcome, an observational unit, and a comparison. Add the period, the population covered, and any planned exclusions. A few clear sentences will help you decide which variables you need and which conclusions your material cannot support.

A row might represent a person, a business, a visit, or a person in a particular month. Confusing these units changes the meaning of every calculation. If one person appears twelve times because you have monthly records, that is not twelve different people. Before counting anything, establish what you are counting and which field, or combination of fields, identifies each observation.

Prepare a simple data dictionary with each variable's name, meaning, unit, permitted values, and missing-value conventions. If a column contains income, specify gross or net, monthly or annual, and the currency. This may feel less exciting than fitting a regression, but it prevents mistakes that no statistical model can repair afterwards.

Use menus to discover and commands to keep a record

The Results window shows Stata's output, the Command window accepts instructions, and the History window records commands that have been run. Other tools let you inspect variables and view observations. Menus are a useful way in: they help you find an operation before you know its syntax, and many operations reveal the corresponding command.

Try a simple task through a menu, then read the instruction that appears. Which part names the variables? Which part selects observations? Which options follow the comma? Recognising these patterns is more useful than memorising isolated lines. For example, help summarize opens the help for descriptive summaries and provides a route to related examples.

Use browse when you want to inspect data without accidentally changing a cell. Keep manual edits for justified, documented situations. If the supplier confirms that a value is wrong, record the correction in your preparation process rather than leaving its explanation only in your memory. The aim is not to do everything through the keyboard; it is to preserve an understandable history of the analysis.

Organise the project before writing your first do-file

A do-file is a text file containing instructions that Stata executes in order. Save it within a project folder with a simple structure: raw for originals, code for programs, and output for generated results. You can add a prepared-data folder as the project grows. Keep the original inputs unchanged so that preparation can always be traced back to its starting point.

Avoid scattering personal file paths across twenty lines of code. Work from the project directory and use relative paths such as output/figure.png. Someone receiving the project should be able to begin by setting that folder as the working directory. Add a short note explaining where the inputs are, which program runs first, and which software version you use.

Write comments that explain decisions, not merely actions. “Exclude records without consent under the study protocol” gives context; “delete rows” gives very little. Divide the program into small blocks for import, validation, preparation, analysis, and export. When something fails, this structure helps you find the problem without reconstructing an entire session of improvised experiments.

Keep original inputs unchanged and document every transformation. One traceable workflow connects validation, preparation, analysis and handover without depending on manual changes that cannot be reconstructed later.
Keep original inputs unchanged and document every transformation. One traceable workflow connects validation, preparation, analysis and handover without depending on manual changes that cannot be reconstructed later.

Import Excel or CSV without losing information

For a worksheet whose first row contains variable names, a starting template is import excel "raw/survey.xlsx", sheet("Data") firstrow clear. For a CSV, try import delimited "raw/survey.csv", varnames(1) clear. These are templates rather than universal instructions: the file, worksheet, delimiter, and other settings must match your actual input.

The clear option allows the data currently in memory to be replaced. Save anything you need before using it. After import, check the number of observations, column names, and a selection of rows. A command finishing without an error does not prove that dates, decimal marks, special characters, or identifiers were interpreted correctly.

Postal codes and identifiers with leading zeros often need to remain strings. An identifier does not become a measurement merely because it consists of digits. For CSV files, stringcols() lets you specify columns to import as strings; consult the help to select the right ones. Also establish whether a comma is a decimal mark or a field delimiter. Those are different issues and require different checks.

Before continuing, compare several imported records with the original file. Include a date, a missing value, and a name containing an accented character. A small, deliberate inspection often finds problems that are invisible if you only glance at the first few rows.

Your first checks: structure, ranges, and categories

describe gives an overview of the dataset's structure. codebook helps inspect individual variables more closely. summarize provides numerical summaries, while tabulate is useful for categorical variables. You do not need to run everything on every column. Start with identifiers, the main outcomes, and the variables that define your study population.

Look for impossible values and unexpected values, which are not the same thing. A negative age may indicate a coding problem; a very high age may be correct but worth checking. Do not remove extremes simply because they are far from the mean. Examine units, recording errors, duplication, and context before deciding whether a value should be changed or excluded.

If a supposedly numerical field imports as text, find out why. It may contain currency symbols, spaces, or a word used to represent missing information. Avoid forcing a conversion before inspecting which entries would be lost. Keep the original variable when a transformation matters, and document the conversion rule so that another person can review it.

Missing values can change more than the sample size

Stata's ordinary numerical missing value is a dot, and extended numerical missing values also exist. Empty strings are a separate case. The missing() function helps check for missing information without confusing it with an observed zero. Do not automatically fill gaps with zero: “did not respond” and “reported no income” are different statements.

There is an important detail when filtering: numerical missing values sort above ordinary numbers. A condition such as income > 1000 can therefore include them. To select observed income above that threshold, use an explicit condition such as income > 1000 & !missing(income). Always check how many observations the filter selects rather than assuming it expresses what you intended.

Count missing values by variable, but also consider how they overlap. A model using five fields can have many fewer complete observations than a summary of one column. Report the sample actually analysed and consider whether exclusions change its composition. Choosing an imputation strategy requires additional reasoning; it is not simply an automatic repair of an inconvenient file.

Duplicates and joins start with a definition of uniqueness

Two identical rows are not always mistakes, and two different rows may still refer to the same unit. If you expect one observation per person, check uniqueness with isid person_id. With monthly records, you might need isid person_id month. A failure is a reason to investigate, not an instruction to delete rows until the command stops complaining.

duplicates report person_id helps identify repeated identifiers. Inspect the records concerned: they might be legitimate visits, corrected versions, or duplicated export records. The solution depends on their meaning. Arbitrarily retaining the first row can remove precisely the information that the analysis needs.

When joining files with merge, choose the correct relationship, such as one-to-one or many-to-one. Validate keys in both files and inspect the _merge variable that describes matches. Do not immediately discard unmatched records. A surprisingly low match rate can reveal inconsistent formats, different periods, or the wrong understanding of an identifier.

A small exercise using data supplied with Stata

To practise without personal information, we will use auto, the automobile example dataset opened by sysuse auto, clear. This is historical teaching material, not a sample of today's car market. It lets us examine price, weight, and origin while following a complete process without relying on an external download.

The variable price records prices in dollars, and weight records weights in pounds. We will create a new kilogram variable rather than overwrite the original. The variable foreign distinguishes the dataset's origin categories. Read its labels before interpreting the numerical code: zero and one do not explain their own meaning.

Our question is descriptive: how are price and weight related in this sample, and what changes when origin is included? We are not estimating the causal effect of manufacturing heavier cars or recommending a vehicle. Keeping that boundary clear makes the conclusions proportionate to the example.

The complete do-file for the exercise

Create the output folder first and set the working directory to the project root. Use a session with no unsaved data that you need to keep. The replace options overwrite the specified output files, so reserve those names for this exercise. The syntax has been checked against official documentation; this is not presented as a Stata execution or performance test carried out by Licendi.

version 18.0
set more off
log using "output/auto-demo.log", text replace name(auto_demo)
sysuse auto, clear
describe
summarize price weight mpg
tabulate foreign, missing
count if missing(price, weight, foreign)
generate double weight_kg = weight * 0.45359237
label variable weight_kg "Weight (kg)"
scatter price weight_kg, name(price_weight, replace)
graph export "output/price-weight.png", width(1920) height(1080) replace
regress price c.weight_kg i.foreign, vce(robust)
count if e(sample)
log close auto_demo

The text log keeps the session's instructions and results, while the graph is exported separately. If an interruption leaves the named log open, close it with log close auto_demo before running the block again. Read the first error message carefully. Repeatedly trying the final lines can conceal the fact that an earlier step never completed.

What to inspect in summaries and graphs

Start with each variable's observation count rather than its average. If counts differ, investigate missing values. Then compare the minimum, maximum, and spread with the units you expect. For a skewed distribution, extend the summary with summarize price, detail and examine the median and percentiles as well as the mean.

The scatterplot positions each automobile by weight and price. Look for the general shape of the relationship, isolated observations, and possible groups. An upward-sloping cloud is not a causal law. Brand, equipment, and other unmeasured characteristics may be associated with both variables. The graph helps generate questions and detect problems; it does not finish the investigation.

Before placing a figure in a report, check axis titles, units, and readability at the final display size. A high-resolution export can still be hard to read if its labels are tiny. For an accessible document, include a short explanation of the relevant pattern that does not rely exclusively on colour.

Read a regression without asking it to prove too much

In the example, regress relates price to weight and origin. The c. prefix treats weight as continuous; i. identifies a categorical variable so that Stata can handle its categories. Check the reference category before interpreting coefficients. A comparison is always expressed relative to something.

The weight coefficient describes an association adjusted for the origin variable included in the model, expressed per kilogram. If that scale is awkward, you can explain a change of one hundred kilograms, provided you state how the unit was converted. Do not confuse coefficient size with uncertainty, or a small p-value with practical importance.

The vce(robust) option changes the uncertainty estimate to accommodate certain forms of heteroskedasticity. It does not repair omitted variables, measurement error, dependence between observations, or an unjustified causal claim. Complex surveys, panels, and clustered observations require attention to their design and appropriate methods; this line is not a universal recipe for every dataset.

Inspect the estimation sample, confidence intervals, and consistency with the graph. If a result is surprising, return to the data and the question. A more complicated model is not necessarily a better answer. Sometimes the real improvement is correcting a unit or making a limitation explicit.

Before interpreting regression, check the sample, units, reference category, uncertainty and assumptions. An association alone does not establish a causal relationship.
Before interpreting regression, check the sample, units, reference category, uncertainty and assumptions. An association alone does not establish a causal relationship.

Reproducibility means someone else can follow the route

Saving the do-file is necessary, but it is not enough. Keep the input-data version, dictionary, supporting programs, and instructions describing the execution order. If data change over time, identify the exact delivery with a date or version label. Otherwise, two people can run identical code on different inputs and obtain different results without understanding why.

The instruction version 18.0 declares the compatibility context for this example's code. It does not install functions unavailable in older software, convert one licence into another, or freeze every external component. If you add community packages, record their names, versions, and sources, and review their requirements before making the project depend on them.

For random procedures, document the seed where relevant. With confidential information, distinguish reproducibility from public release. You do not need to distribute personal data to explain your method. You may share code and an anonymised or synthetic example structure, provided you state honestly what that material can verify and what requires authorised access.

Which Licendi licence fits this learning project?

The basic commands in this guide do not require MP simply because you are learning. Your choice should follow dataset size, required methods, hardware, and usage conditions. The catalogue entries reviewed for Stata 18.0 and Stata 19.0 offer Windows or Mac and BE, SE, or MP editions. Check the selected variant before adding it to the basket.

Catalogue exampleWhat to checkWhen to consider it
Stata 18.0 permanentOperating system, edition, and the 2-core MP optionLearning and projects compatible with that generation
Stata 19.0 permanentOperating system, edition, and the 4-core MP optionProjects requiring that generation and its specific functions

Within a generation, BE, SE, and MP differ mainly in capacity and processing. Parallel multicore processing belongs to MP: a commercial reference to cores does not turn SE or BE into MP. Nor does four-core licensing mean every task takes half as long. Avoid buying capacity you do not need or assuming a speed increase without assessing your actual workload.

A permanent licence for a version does not automatically include future major releases, StataNow, maintenance, or unlimited transfer rights. Read the offer's terms and confirm institutional requirements before purchasing. For a generation-focused discussion, see our Stata 18 versus Stata 19 comparison. This tutorial is concerned with the analysis workflow rather than a list of new features.

Common mistakes to avoid from the start

The first is working on the only original file. The second is making manual corrections without recording them. The third is interpreting output before checking units and sample composition. None is solved by buying a higher edition. They are solved by simple habits and stage-by-stage review rather than leaving all checks until the evening before delivery.

Another common problem comes from running only part of a do-file. That fragment may depend on a variable created earlier or a data selection that is no longer active. When the program appears finished, run it from the beginning in a clean session using the intended inputs. A fragment that works is not proof that the complete process is reproducible.

Do not hide inconvenient messages. If a merge leaves records unmatched, a model reduces the sample, or a conversion creates missing values, explain what happened. Maintain a small decision log with the date, problem, solution, and reason. It is far more useful than a folder containing files named “final”, “final2”, and “really_final”.

A useful rehearsal is to give yourself a deliberately imperfect copy of a small input file. Add a repeated identifier, leave one outcome blank, and change one unit label. Keep the unmodified original separately. Then ask whether your checks detect each change before the analysis starts. This is a training exercise, not a reason to alter real source data or invent observations for a report.

For each issue, write down the expected response. A repeated person identifier might be acceptable in visit data but not in a one-row-per-person file. A missing outcome might reduce an estimation sample, while an inconsistent unit should stop a comparison until it is understood. The objective is to turn assumptions into explicit checks rather than rely on remembering them.

Finally, remove the deliberate mistakes from the exercise copy and run the complete workflow again. Compare the output with the original training run and explain any remaining difference. This simple habit teaches you to test the preparation process itself, not just admire the final chart. It is also a useful way to show a colleague what the project's validation rules are intended to catch.

Dates, units, and weights deserve separate attention

A date that looks right in a spreadsheet may enter Stata as text, a number, or an already interpreted date. Check its type and meaning before filtering periods. A display format alone is not a conversion: changing how a number looks does not automatically turn a string into a valid date. Consult the date functions and test records whose day and month cannot be confused.

Units require the same care. Comparing sales recorded in thousands of euros with costs recorded in euros can produce extraordinary-looking results that are simply scale errors. Keep units in labels and in the dictionary. When converting quantities, create a new variable and document the conversion factor, as we did with pounds and kilograms.

Statistical weights are not just another column. A survey weight, a frequency, and an analytical weight have different meanings. Do not add a weight to a model solely because one exists in the file. Find out how the sample was constructed, which population it represents, and which weighting method the procedure requires. For complex surveys, consult the methodological documentation before interpreting estimates and uncertainty.

Prepare a table that makes sense outside Stata

Your report's reader may never see the software. A useful table explains what was measured, in which units, over how many observations, and during which period. Identify comparison groups clearly and avoid headings that merely repeat abbreviated variable names. “Monthly household income, euros” communicates much more than “inc_hh”.

Choose decimal precision according to the measurements and the report's purpose. Six decimal places add little if the original measurement was approximate. Apply a consistent approach across tables and figures, and distinguish counts from percentages. Be especially clear about the denominator: a percentage of valid responses can differ from a percentage of everyone invited to respond.

When reporting models, include uncertainty alongside coefficients and explain which variables were included. Do not copy only the line that looks most favourable to your hypothesis. If you tried alternative specifications, document why you chose the main one and what changes under the others. Presentation is part of analysis: it should help readers evaluate evidence rather than force them to guess how you reached the conclusion.

A careful handover protects both time and data

Before sharing a project, inspect every folder. Logs may contain filenames, local paths, and values displayed during checks. Screenshots can also reveal information you did not intend to send. Share only necessary material and use your organisation's approved channels when confidential information is involved.

Add a short instruction file covering the objective, input source, execution order, Stata version, dependencies, and expected outputs. It need not become a huge manual. Someone who did not attend your working sessions should be able to distinguish originals from generated files and understand what is needed to reproduce the work. Include known limitations and any step requiring permission or manual intervention.

Keep an identifiable copy of the delivery. If a table changes several weeks later, you can compare code and inputs between versions instead of reconstructing events from memory. This discipline is particularly useful when several people review a report: it separates a genuine correction from a difference in file, configuration, or extraction date.

A realistic plan for your first week

Use the first session to open a file, understand its variables, and write a specific question. In the second, practise importing and compare the result with the original. In the third, add checks for identifiers, ranges, and missing values. Once those steps are clear, prepare a descriptive table and one figure that address the original question.

Set aside another session to turn that journey into an organised do-file. Then close everything and rerun it using only your written instructions. Undocumented steps will quickly become visible. If possible, ask someone else to repeat it: their questions reveal details that seemed obvious only because you had built the project yourself.

You do not need to master advanced regression in one week. A better goal is being able to explain where every number in a small report came from. From there, expand into models, surveys, panels, or automation as your needs develop. Official documentation and learning resources are a more dependable starting point than copying commands without understanding their context.

Start your purchase with the work you want to repeat

Learning Stata means connecting questions, data, and decisions transparently. Once you understand each row, how variables were prepared, and which sample feeds a result, the software becomes a working tool rather than a collection of commands. That clarity also improves purchasing decisions: define the need first, then select the version, edition, and platform.

Review the Stata 18.0 licence at Licendi or the Stata 19.0 licence at Licendi with that approach. Begin with a manageable project, preserve the originals, and build a do-file another person can follow. Your first analysis does not have to be spectacular. It needs to be understandable, checkable, and repeatable with confidence.

Documentation for your next steps

Explore Stata's interface, the do-file manual, delimited-file import, the merge manual, and the regress documentation. Version-specific references help distinguish these established functions from later additions. Consult your installed help for the exact options supported by your software.