generate: create variables from expressions
Turn existing columns into calculated measures and indicators while choosing where and how the new values are stored.
Independent software. Not affiliated with, sponsored by, or endorsed by StataCorp LLC.
Complete example
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 a row function such as the supported egen rowmean() when the intended rule is to average the available components instead.
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. 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.
Open this example