Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Interface and Data

Data Types and Storage in Stata

Understand Stata storage types byte, int, long, float, double and strings, display formats, destring, tostring, encode, compress and how Stata stores dates.

Every Stata variable has a storage type, and the type decides what values it can hold and how much memory it uses. Types explain several surprises: why 0.1 is not exactly 0.1, why a column cannot be averaged, and why a date looks like 22000. This lesson covers numeric and string types, display formats, converting between them, and how dates are stored.

Two families: numeric and string

Type Holds Range or size
byte Small integers -127 to 100
int Integers -32,767 to 32,740
long Larger integers about -2.1 billion to 2.1 billion
float Real numbers about 7 significant digits (default for generate)
double Real numbers about 16 significant digits
str1 ... str2045 Text up to that length one byte per character
strL Very long text or binary up to 2 billion bytes

describe shows the type next to each name. When you type generate x = 1, Stata chooses the type for you. Normal generate makes a float for non-integer results and an integer type when the whole column fits.

Numbers are stored in binary, so decimals like 0.1 are only approximate. Compare floats carefully: the statement if x == 0.1 can be false for a float variable. Use double for ids and for money you must not round, and compare with a tolerance (abs(x - 0.1) < 1e-6) if needed.

STATA
generate double precise = 1/3     // force double precision
generate byte female = (sex == 2) // an indicator in one byte
describe

Large ids need long or double. A float keeps only about 7 digits, so a 9-digit identifier stored as float silently loses its last digits. Storing ids as str or double avoids that.

Display formats

The format controls how a value is shown, not how it is stored.

STATA
format income %9.2f          // 9 wide, 2 decimals
format income %12.0gc        // thousands separators
format rate %5.1f
format when %td              // show as a daily date
describe income

A format is a percent sign, a width, a dot and the number of decimals, followed by a letter: f fixed, g general, e scientific, s string. Adding c adds commas. Changing the format never changes the data: the underlying value stays the same.

Storing memory economically

STATA
compress                      // choose the smallest type that holds the data

compress reviews every variable and demotes double to float, long to int and long strings to shorter ones when no information is lost. It is a safe way to shrink a big file before saving. It will not change data values.

Converting between strings and numbers

Imported numbers that came in as text can be repaired in three ways:

STATA
destring income, replace                 // convert text to numbers if possible
destring income, replace ignore("$,")    // remove $ and , characters first
destring income, generate(income_n) force // non-numeric text becomes missing
tostring zip, replace                    // number to text
tostring zip, replace format(%05.0f)     // keep leading zeros: 02134

destring refuses to convert when some text is not a number, unless you add force. Read the message and inspect those values before using force.

encode turns text categories into a labelled numeric variable, which many commands require (for example i.region in regression):

STATA
encode region, generate(region_n)   // North=1, South=2 ... with value labels
decode region_n, generate(region_s) // back to text

encode numbers the categories in alphabetical order and stores the original text as a value label. Never use destring on categories such as "North": it only handles text that already looks like numbers.

flowchart LR
    A["String of digits<br/>(text 41000)"] -->|"destring"| B["Number"]
    B -->|"tostring"| A
    C["String categories<br/>(text North)"] -->|"encode"| D["Labelled number"]
    D -->|"decode"| C

Which command moves between text and numbers.

Dates

Stata stores a date as a number of days since 1 January 1960 (day 0). Format it with %td to see it as a date.

Kind Format Counted as
Daily %td days since 01jan1960
Weekly %tw weeks since 1960w1
Monthly %tm months since 1960m1
Quarterly %tq quarters since 1960q1
Yearly %ty the year number itself
Date and time %tc milliseconds since 01jan1960 00:00:00
STATA
generate day = date(datestr, "YMD")         // text "2024-03-15" to a Stata date
format day %td
generate month = mofd(day)                  // monthly date from daily
format month %tm
generate year = year(day)
generate dow = dow(day)                     // 0 = Sunday
display td(15mar2024)                       // the number for 15 March 2024

The mask in date() tells Stata how the text is ordered: "YMD", "DMY", "MDY". A wrong mask silently produces missing values or wrong dates, so check with list after converting. You can also build a date from parts: generate d = mdy(month, day, year).

Counting days since 1960 explains why the number 22000 is a valid date: it is around 2020. Daily subtraction gives the gap directly (generate age_days = today - birth), which is the reason dates are numbers in the first place.

Stand-ins: date arithmetic and float error

Python's datetime can model the Stata date number: the epoch is 1960-01-01. The first block converts both ways; the second shows why float storage loses precision (we emulate it with struct to get a real 32-bit float).

Python Stand-in: Stata date numbers

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.

Python Stand-in: float versus double

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.

You should see that a nine-digit id changes when stored in a 32-bit float, and that 0.1 is not the same value as its float copy. This is exactly why Stata users store identifiers as long, double or str.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A nine-digit id stored as float will:

    A float holds about 7 significant digits, so large ids should be long, double or string.
  2. 2. Which command turns the text categories North, South, West into labelled numbers?

    encode creates a labelled numeric variable from text categories.
  3. 3. How does Stata store a daily date?

    %td dates are days since 01jan1960; the format controls how they are shown.
  4. 4. What does format income %9.2f change?

    A display format never changes the data, only how it appears.

Summary

  • Types are byte, int, long, float, double and str#/strL; describe shows them; compress shrinks them safely.
  • Floats are approximate and keep about 7 digits, so use double, long or string for ids and exact money.
  • destring, tostring, encode and decode move between text and numbers; force hides bad values, so look first.
  • Display formats such as %9.2f and %td change appearance only.
  • Dates are day counts from 01jan1960 and must be formatted and checked after date().

Next: Missing Values and Labels