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
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
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.