Generating variables in Stata

April 19, 2019

Generating new variables in Stata is mainly achieved by use of the gen command. The simplest way to use the is by appending the newvar option, by specifiying the name and value of the new variable.

gen my_var = 0
tab my_var

Generating a new variable

Here we just generated a new variable called my_var in the nlsw88 dataset, which has the value of 0 for every observation in the data. Not very useful though.

Instead a variable can be generated that stores some calculation on the data. Using the auto dataset for example we can generate a variable that calculates price per inch:

sysuse auto, clear
gen price_per_inch = price/length
su

By summarizing the dataset we can see that some cars have a lower price per inch than others:

Price per inch


Profile picture

Written by Johan Osterberg who lives and works in Gothenburg, Sweden as a developer specialized in e-commerce. Connect with me on Linkedin

2024 © Johan Osterberg