generate: create variables from expressions
Turn existing columns into calculated measures and indicators while choosing where and how the new values are stored.
Generate a new variable and indicator
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
The first expression calculates a row-level average. The second creates a zero/one indicator and explicitly stores it as byte.
Output from stats.camp
+--------------------------------------------------------------+ | # id read write math score_average high_math | |--------------------------------------------------------------| | 13 13 46 48 47 47 0 | | 14 14 54 56 55 55 0 | | 15 15 49 50 0 | | 16 16 57 59 58 58 0 | +--------------------------------------------------------------+
How to read the result
Rows 13, 14, and 16 have averages of 47, 55, and 58. Row 15 has a missing write value, so ordinary arithmetic propagates that missing value into score_average. Its math score is below 60, so high_math is zero.
Use the supported egen rowmean() function when the intended rule is to average the available components instead.
Create a cumulative sum with generate sum()
Sort the data into the intended sequence before calculating a running total:
sort id
generate cumulative_math = sum(math)
list id math cumulative_math in 1/6
+-------------------------------------+ | # id math cumulative_math | |-------------------------------------| | 1 1 45 45 | | 2 2 51 96 | | 3 3 43 139 | | 4 4 56 195 | | 5 5 48 243 | |-------------------------------------| | 6 6 60 303 | +-------------------------------------+
sum(math) accumulates values in the current observation order. Sorting by a stable identifier makes that order explicit; sorting differently can produce a different cumulative sequence.
Common syntax and safeguards
genandgare supported abbreviations forgenerate.- Specify storage types such as
byte,int,long,float,double, or a string type when representation matters. - Use
ifandinqualifiers to generate values only for selected observations; unselected rows are missing in the new variable. - Under a supported
byworkflow,_nand_Nrefer to the row number and size within the current group. - A running
sum()follows the current sort order and treats a missing numeric value as contributing zero to the cumulative total. generatewill not silently overwrite an existing variable. Usereplaceonly after confirming that mutation is intended.
See the current generate entry and Stata's generate and replace manual for an external reference.
Related guides
Run this exact example
Clone the example repository in stats.camp and open the exact do-file shown on this page. No stats.camp account is required.
Run the variable-generation example