Doctors Revision

STATA for Biostatistics and Epidemiological Data Analysis

Text size
On this page 20 sections

Overview

Clinical Medicine Year 2 • Biostatistics and epidemiology

STATA for biostatistics supports data management, statistical analysis, graphics and reproducible reporting in clinical and population-health research. Its command language is especially useful for recording an analysis in a do-file so that the steps can be reviewed and repeated. The software does not choose the right question or guarantee valid conclusions: analysts must first understand the protocol, unit of analysis, data quality, study design and assumptions.

Learning outcomes

By the end, you should be able to describe STATA’s basic workflow; import and inspect health data; label and check variables; document missing values and transformations; produce descriptive summaries; select appropriate basic analyses; interpret regression output cautiously; and save do-files and logs for reproducibility.

1. What STATA does in a health-research workflow

STATA is a statistical software environment for managing, analysing and graphing data. A typical participant-level dataset has one observation per participant and one variable per column. It can be used for frequencies, summaries, group comparisons, regression and many specialised analyses. Features and syntax can differ by version and licensed edition, so check the manual installed with your institution’s version.

It cannot fix an unrepresentative sample, a poorly defined outcome, inaccurate measurements, unapproved access to identifiable records or confounding caused by design. Nor does a statistically significant result automatically matter clinically. Software is the tool; the protocol and statistical reasoning determine what the output means.

2. Set up files and protect data

Create clearly named folders for protocol, unchanged raw data, cleaned data, do-files, logs, output tables and reports. Save a new working copy before recoding or deleting anything. Use an approved study identifier, avoid unnecessary direct identifiers, restrict access to identifiable data and follow the approved retention and sharing plan. Do not email or upload identifiable health records to unapproved services.

Plan each analysis before running commands: which objective it answers, the outcome, exposure, comparison, summary or model, possible confounders, missing-data approach and relevant subgroup analyses. This prevents exploratory fishing from becoming a misleading confirmatory claim.

3. Understand observations, variables and data types

In the Data Editor, rows usually represent observations and columns represent variables. Numeric variables may be counts, measurements or numeric codes; string variables contain text; dates should be stored in a format that supports correct time calculations. A number code is not necessarily a quantity: codes 1, 2 and 3 for categories should not be averaged as if category 3 were “three times” category 1.

Variable Role and type Example label / values Check
VariableRole and typeExample label / valuesCheck
study_idIdentifier; string or numericUnique participant codeNo duplicates; contains no direct identifiers.
age_yearsContinuous numericAge in completed yearsPlausible values and units.
facilityCategorical numeric or stringFacility code with value labelsValid codes match the sampling sites.
stockoutBinary categorical0 = no; 1 = yes under the protocol definitionConfirm recall period and source.
missed_visitBinary outcome0 = attended; 1 = missed within prespecified grace periodDenominator and date rule are explicit.
sbp_mmHgContinuous measurementSystolic blood pressure in mmHgCheck device, repeated values and outliers.

Labels improve readability, while value labels explain codes. Maintain a separate data dictionary that records definitions, units, response options, missing codes, source, derived-variable formula and any recoding rationale.

4. Start a do-file and log

A do-file is a text file of STATA commands. It should include comments, the project purpose, dataset version, date and the planned sequence. A log records commands and output from an analysis session; choose text or SMCL format according to your workflow. Store files securely and avoid logging confidential information unintentionally. Example setup:

* Example template: change paths and variable names to your approved project.
clear all
set more off
capture log close
log using "analysis_log.txt", text replace
import delimited "cleaned_health_data.csv", clear
save "analysis_working_copy.dta", replace

Use a project-specific folder rather than assuming that the current directory is correct. Before running, verify the file path and never allow a template command to replace an authoritative raw file.

5. Import and inspect data before analysing

For a comma-separated file, import delimited reads the data; for a Stata file, use loads it. After import, inspect the dataset using describe, codebook, list on a small authorised sample and browse. Check the number of observations and variables, names, storage types, labels and unexpected string or numeric conversions.

Run one-way tabulations for categorical variables and summary statistics for quantitative ones. Compare key values against the source tool, check duplicate study IDs, impossible dates, inconsistent units, invalid codes and missingness. Save a cleaned copy under a new version name. Investigate outliers against source records and the data-correction procedure; do not delete a value just because it changes a result.

6. Missing values and coding decisions

In STATA, numeric missing values are represented by a dot and are larger than every numeric value in comparisons. Extended missing values such as .a can distinguish reasons, but they should be used only with a documented rule. Blank strings, “not applicable,” “not recorded” and true zero are not interchangeable. Review missing data using tools such as misstable summarize and examine patterns across the variables and groups that matter.

Do not silently convert missing entries to zero, drop incomplete cases without assessing consequences or assume that missingness is random. Specify a defensible approach in the analysis plan, report how much data were missing, and seek statistical advice when missingness is substantial or the chosen method is complex.

7. Label, recode and derive variables

Commands such as label variable and value-label definitions make output understandable. Use generate to create a new derived variable, and replace only when the intended transformation is clear and documented. Prefer a new variable to overwriting original responses. For example, when calculating BMI, retain weight and height, confirm units, apply the formula only to valid measurements and document any exclusion rule.

Recode continuous variables into categories only when a clinically or analytically justified threshold exists. Categorisation discards information and may obscure patterns. If the aim is simply to describe age, keeping age continuous is often more informative than inventing “young” and “old” groups.

8. Describe the sample first

Question STATA command or route What to report
QuestionSTATA command or routeWhat to report
How many in each category?tabulate variableCounts, percentages, valid denominator and missing count.
What are centre and spread?summarize variable, detail or tabstatMean/SD for suitable distributions; median/IQR for skewed data.
How does a continuous measure vary by group?by group, sort: summarize measureGroup-specific estimates and units.
What is the pattern over time?Time-series or graph commands suited to the sampling intervalTime period, denominators and any seasonal structure.

Check whether the summary answers the objective and whether a percentage uses the right denominator. A high count at a busy referral hospital is not automatically a high population rate. Report the source population and selection process so readers can judge representativeness.

9. Choose a procedure that matches design and variables

Research question Possible STATA procedure Key caution
Research questionPossible STATA procedureKey caution
Compare a mean in two independent groupsttest outcome, by(group)Check independence, distribution, outliers and variance; report a difference and interval.
Compare the same people before and afterPaired t-test or a suitable paired rank procedureUse the within-person structure, not an independent-group test.
Compare categorical variablestabulate exposure outcome, row chi2Inspect expected counts, denominators and the sampling design.
Model a continuous outcomeregress outcome exposure confoundersAssess linearity, residuals, influential points, independence and variance assumptions.
Model a binary outcomelogistic outcome exposure confoundersReport odds ratios and confidence intervals; odds ratios are not always risk ratios.
Assess ranked or monotonic associationspearman x yAssociation is not agreement or causation.

This table is a starting point, not an automated rule. Consider paired or clustered observations, repeated measures, sampling weights, sparse data, confounders, effect modification and missingness. If a sample is clustered by clinic or uses a complex survey design, standard commands may give incorrect uncertainty unless the design is accounted for. Advanced survival, multilevel, causal or survey analysis needs an appropriate plan and expertise.

10. Worked example: stock-outs and missed follow-up

Illustrative values only, not real study results: suppose 100 participants report a medicine stock-out and 100 do not; 20 and 10 respectively miss follow-up. The group proportions are 20% and 10%, with a crude difference of 10 percentage points. If the outcome period and denominators are as specified, the crude risk ratio is 2.0. These descriptive contrasts do not prove that stock-outs caused missed visits; travel distance, disease severity, clinic scheduling or other factors may explain some of the association.

First check coding and denominators. A two-way table can show counts and row percentages; request a chi-square test only when the design and expected counts support it. For an adjusted analysis with a binary outcome, a logistic model might include stock-out and prespecified confounders. Do not choose covariates solely because their univariable p-values are small, and do not claim that adjustment removes unmeasured confounding.

* Illustrative commands; adapt to your variable names and protocol.
tabulate stockout missed_visit, row chi2
logistic missed_visit i.stockout c.age_years i.facility
estimates store adjusted_model

11. Interpret estimates, uncertainty and p-values

In a linear regression, a coefficient is an estimated change in the outcome per unit increase in a predictor, conditional on the included variables and model. In logistic regression, exponentiating a coefficient gives an odds ratio. Read the reference category carefully, check the confidence interval and state the units. A confidence interval reflects uncertainty under the model; it does not capture every risk of selection bias, measurement error or confounding.

A p-value is not the probability the null is true and is not a measure of effect size or clinical importance. A small effect can be statistically detectable in a large sample, and an important effect can have a wide interval in a small sample. Report effect estimates, confidence intervals, denominators and limitations; interpret findings in context.

12. Tables and graphs

Use a graph that answers a specific question: bar charts for categories, histograms for distribution, box plots for group comparisons, and scatterplots for relationships between continuous measurements. Label units, denominators and time periods. Avoid distorted axes and overcrowded legends. Verify every exported table against the STATA output and ensure that rounding does not imply more precision than the data support.

13. Reproducibility and version control

Save the original data, cleaned data, do-file, log and final tables separately. Note the STATA release and user-written commands if relevant; a program unavailable to another analyst can prevent reproduction. Record package names and versions, avoid running unreviewed commands from untrusted sources, and keep a brief change log. Test the do-file from the beginning on a clean working copy before finalising a report.

14. Common errors and exam points

15. Mini case and review questions

A facility team wants to know whether travel time is associated with late antenatal booking. Define “late” using the study’s stated clinical or programme definition, specify how travel time will be measured, identify the eligible population and period, inspect missing gestational-age data, and consider access to transport and referral patterns. Ask whether the planned design establishes temporal order and what conclusions it can support.

  1. What is the difference between an observation and a variable?
  2. Why keep the original variable after recoding?
  3. Which STATA command can show counts and row percentages for two categorical variables?
  4. What does a logistic-regression odds ratio compare?
  5. Why should estimates be presented with uncertainty and design limitations?

Continue learning

For parallel software practice, read SPSS for biostatistics and Microsoft Excel for health data analysis. Review confidence intervals in health research, research designs and the Clinical Medicine Year 2 curriculum.

References and further reading

Educational revision content only. Follow the approved protocol, data-protection requirements and institutional analysis standards. Seek qualified statistical advice for complex designs, clustered data, missing-data methods or high-stakes interpretation.

Further Reading

For deeper study, use official statistical-software and research-analysis resources:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top