Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 36 ยท Interface and Data

Importing Data into Stata

Load data into Stata with use, sysuse, webuse, import delimited and import excel. Learn options for headers, delimiters, encodings, sheets and how to check the result.

Real analysis starts with a file from somewhere else: a survey export, a spreadsheet from a colleague, a download from a statistics office. Stata can read many formats, and the command you choose depends on the file type. This lesson covers the common ones and, more importantly, the checks you must do right after loading, because a silent import mistake can ruin a whole project.

Stata's own format: .dta

Datasets saved by Stata end in .dta. They keep variable types, labels and value labels. Load them with use:

STATA
use "data/raw/survey.dta", clear           // whole file
use age income region using "survey.dta"   // only some variables (saves memory)
use "survey.dta" if age >= 18, clear       // only some observations

The clear option throws away the data currently in memory. Without it, Stata refuses to load if the current data have unsaved changes (error r(4)). You can also load practice data:

STATA
sysuse auto, clear        // example data installed with Stata
webuse nlswork, clear     // example data from the Stata website (needs internet)

webuse is how the manuals' examples are loaded; it is a quick way to follow along with the documentation.

To peek inside a file without loading it: describe using "survey.dta".

CSV and text files: import delimited

CSV (comma-separated values) is the exchange format of the world. The command is import delimited:

STATA
import delimited "data/raw/survey.csv", clear
import delimited using "survey.csv", varnames(1) clear   // first row holds names
import delimited "survey.txt", delimiter(";") clear       // semicolon-separated
import delimited "survey.tsv", delimiter(tab) clear       // tab-separated
import delimited "survey.csv", encoding(UTF-8) clear      // accented characters

Useful options:

Option Purpose
varnames(1) Use row 1 as variable names (the default if Stata detects it)
varnames(nonames) The file has no header; variables are named v1, v2, ...
delimiter(";") Choose the separator; also tab, space, comma
rowrange(2:500) Read only some rows
colrange(1:5) Read only some columns
encoding(...) Fix garbled characters, such as UTF-8 or latin1
case(preserve) Keep the capital letters of names (the default converts to lowercase)
stringcols(1 3) Force certain columns to be read as text
numericcols(4) Force a column to be numeric
clear Replace the data in memory

Stata names variables from the header, converting invalid characters (spaces, -) to underscores and making names lowercase. A header like Annual Income ($) becomes annualincome or similar, and the original text is kept as the variable's label. Check with describe.

Excel: import excel

STATA
import excel "data/raw/budget.xlsx", sheet("2024") firstrow clear
import excel "budget.xlsx", cellrange(B3:F120) firstrow clear
import excel "budget.xlsx", describe          // list sheets and ranges first
  • firstrow treats the first row as variable names.
  • sheet("name") picks a sheet; otherwise Stata reads the first.
  • cellrange(B3:F120) skips titles and notes above the table.
  • allstring reads every cell as text, which is the safest way to inspect a messy sheet before converting types yourself.

Excel stores dates as numbers and mixes types within a column. A column of numbers with one "N/A" cell becomes text, and every later summarize on it says there are no observations. Always check types after importing.

Other formats

STATA
import sas "file.sas7bdat", clear
import spss "file.sav", clear
import dbase "file.dbf", clear
import fred ...                      // economic data, when connected
use "stata12.dta", clear             // older .dta versions read fine

For formats Stata does not read directly, convert to CSV first, or use odbc load to pull data from a database through ODBC. Fixed-width text files use infix or infile with a dictionary that describes the column positions.

Always check what you loaded

Right after import, run these commands and read the output:

STATA
describe                 // number of observations, variable types
list in 1/5              // do the first rows look right?
summarize                // numeric variables show N, mean, min, max
codebook, compact        // one-line summary of every variable
count                    // number of observations
isid id                  // error if id does not uniquely identify rows

What to look for:

  1. Observation count matches the source (open the file in a text editor and count lines).
  2. Variables that should be numeric appear as str types in describe: probably a stray text value.
  3. summarize shows no observations for a variable you thought was numeric: it is text.
  4. Dates come in as text or as a number like 19876; convert them later (data types).
  5. Duplicated ids (isid fails) mean a cleaning step is needed.

Saving: from import to .dta

After you import and check, save to Stata format in your clean folder so you do not have to repeat the import every time:

STATA
save "data/clean/survey_raw.dta", replace

The do-file 01_import.do should end with this line. It is the whole job of that file. Later files start with use "data/clean/survey_raw.dta", clear.

A stand-in: reading CSV and guessing types

import delimited reads the header, splits each line and guesses each column's type: numeric if every value is a number, text otherwise. The Python model below does exactly that on an embedded CSV so you can see how a single bad value turns a numeric column into text.

Python Stand-in: import delimited and guess the types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that income is guessed as text because of N/A. In Stata you would fix this with destring income, replace force, or better, by cleaning the source or reading the column with stringcols/numericcols. The next stand-in shows the conversion and what happens to the bad value.

Python Stand-in: destring with force makes bad text missing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

force makes anything non-numeric missing silently. Use it only after you have looked at what will be lost (tab income if real(income) == .).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command loads a .csv file?

    import delimited reads CSV and other delimited text files.
  2. 2. What does the clear option do in use file.dta, clear?

    clear discards the data in memory so the new file can be loaded.
  3. 3. A numeric-looking column imports as text. Most likely cause?

    One non-numeric entry makes the whole column text.
  4. 4. Which Excel option uses the first row as variable names?

    import excel ..., firstrow takes names from the first row.

Summary

  • use loads .dta files; sysuse and webuse load example data.
  • import delimited reads CSV, TSV and other text; import excel reads sheets with sheet(), cellrange() and firstrow.
  • Options control delimiters, headers, encoding and which rows or columns to read.
  • Always follow an import with describe, list, summarize and isid.
  • Save the imported data to .dta so later do-files start from a clean file.

Next: Data Types and Storage