generate: create variables from expressions

Turn existing columns into calculated measures and indicators while choosing where and how the new values are stored.

Tested 2026-08-16 with the current stats.camp development build · View the do-file on GitHub

Run the variable-generation example View supported commands
Independent software. Not affiliated with, sponsored by, or endorsed by StataCorp LLC.

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

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