Command reference

generate — create a variable from an expression

Create a new variable by evaluating an expression for each observation. Use generate for calculations, indicator variables, copies of existing columns, and running totals.

Syntax

generate [type] newvar = expression [if condition] [in first/last]

newvar must be a name that does not already exist. The expression can use existing variables, numbers, functions, and operators. For example, (read + math) / 2 calculates a mean, while math >= 60 creates a zero/one indicator. Use replace to change an existing variable.

Storage types, expressions, and qualifiers

byte, int, long, float, double
Place an optional numeric storage type before the new name, as in generate byte passed = math >= 60. Integer types discard fractional parts. Numeric variables otherwise use the current default type, initially float; use double for greater precision.
str# or strL
Create a text variable from a string expression. str20 limits stored strings to 20 characters; strL does not impose that fixed width. Put literal text in double quotes.
if condition
Assign values only where the condition is true. The new variable is missing in observations outside the condition; other variables and observations remain in the dataset.
in first/last
Assign only within a range of observation positions, such as in 1/10. Positions follow the current row order, so sort first when order matters.
sum(expression)
Calculate a cumulative sum in the current observation order. This differs from egen total(), which repeats the overall total. With a by: or bysort: prefix, running totals restart within each group.
_n and _N
_n is the current observation number and _N is the number of observations. Under a grouping prefix, they refer to the position and size within each group.

Example

The sample creates a three-subject average and a high-math-score indicator. It then sorts students by ID and creates a cumulative math total. The two listings let you inspect both calculations.

clear
import delimited "data/student_scores.csv"
generate score_average = (read + write + math) / 3
generate byte high_math = math >= 60
list id read write math score_average high_math in 13/16
sort id
generate cumulative_math = sum(math)
list id math cumulative_math in 1/6
Open example in browser

Sample data included. Opens in a new tab; click Run.

What to look for

Student 15 has no writing score, so the arithmetic average is missing even though reading and math are observed. The high_math indicator is 1 for scores of at least 60 and 0 below that threshold. After sorting by ID, cumulative_math adds each student’s math score to the preceding total.