How Does egen and gen Differ in Stata? A Clear Guide With Examples

If you have typed gen mean(score) in Stata and got slapped with an error, you already know the pain.

Quick answer: gen creates a new variable row by row, using a plain arithmetic expression. egen (extended generate) uses a fixed set of built-in functions instead, and it can work across groups of rows, not just one row at a time.

That is the whole confusion in one line. Everything else below is the why and the when.

I have been doing statistics tutoring and dissertation data work for over 12 years now. I work as a stata tutor online with students in the UK, USA and India who deal with survey and panel data every day.

Stata, built by StataCorp, has kept this same gen and egen split since its early versions, and it still confuses first-time users the same way it confused me. I remember the exact week I got stuck on this during my own research days. This guide is written the way I wish someone had explained it to me back then.

What Is gen in Stata?

gen is short for generate. It is Stata’s basic, built-in command for creating a new variable from an expression involving existing variables, numbers, or operators.

It works strictly row by row. Stata reads the expression, applies it to each observation one at a time, and writes the result into the new variable.

Basic syntax:

gen new_variable = expression

Example:

gen avg_score = (maths + english + history) / 3

This takes the three subject marks for each student, averages them for that one row, and stores the result. Simple, fast, and it does exactly what you tell it to.

What gen cannot do: it has no idea what “mean of the whole column” or “group total” means unless you build that logic yourself. It only understands the expression syntax, nothing more.

What Is egen in Stata?

egen stands for extended generate. It was added later to give users access to more complex, pre-built statistical functions that plain gen was never designed to handle.

Here is the part that trips up almost every beginner. egen only accepts functions from its own fixed list, egen functions, and nothing else. You cannot throw a random expression at it the way you can with gen.

Basic syntax:

egen new_variable = function(arguments)

Example:

egen avg_score = rowmean(maths english history)

Same result as the gen example above, but egen handles the row averaging through its own built-in rowmean() function instead of you writing the arithmetic yourself. For the full official function list, university references like Princeton’s Stata tutorial are a solid starting point, though I will cover the ones you will actually use below.

gen vs egen: The Core Differences

Here is the comparison I actually draw on a whiteboard for my students.

Featuregenegen
Full formgenerateextended generate
Works withAny valid Stata expressionOnly pre-defined egen functions
Operates onOne row at a timeCan work across rows, groups, or the whole dataset
SpeedFast, lightweightSlower on large datasets
Missing valuesYou must handle them manually with if conditionsMany egen functions handle missing values automatically
Typical useArithmetic, conditional creation, dummy variablesMeans, totals, group statistics, tagging, ranking

A real dissertation example. Say you are building an anxiety score from five survey items for a psychology dissertation. If every respondent answered all five items, gen works fine:

gen anxiety_score = q1 + q2 + q3 + q4 + q5

But the moment even one respondent skipped a question, that row turns missing, and your total score silently disappears for that person. egen‘s rowtotal() function saves you here. It treats missing values as zero by default:

egen anxiety_score = rowtotal(q1 q2 q3 q4 q5)

I’ve seen this exact mistake quietly wipe out a chunk of usable respondents more than once. It is an easy one to miss until someone points it out. Read more on descriptive statistics in Stata if this kind of missing data handling is new to you.

When to Use gen vs When to Use egen

Use gen when:

  1. You are doing simple row-level arithmetic (sums, differences, ratios)
  2. You are creating a dummy or binary variable based on a condition
  3. You need full control over how missing values are treated
  4. Speed matters and your dataset is large

Use egen when:

  1. You need a statistic that spans multiple rows, like a mean, total, or standard deviation
  2. You need group-level statistics, such as average income by region
  3. You want to rank, tag duplicates, or count unique groups
  4. You are fine trading a bit of speed for convenience

Common mistakes I see students make:

  • Trying to write gen mean_x = mean(x), not realising mean() is an egen function, not something gen understands
  • Using egen for basic arithmetic that gen would handle faster
  • Forgetting that egen functions are their own separate namespace, so a function that works fine inside egen will throw an error if you try to use it inside gen
  • Not combining egen with bysort when they actually needed a statistic calculated per group, not for the whole dataset
  • Reaching for gen to fix an existing variable, when replace is what actually updates values without creating a new column

Here is a quick opinion, since you asked for one. A lot of the university tutorial pages and old Statalist forum threads that explain this topic are technically accurate. But they read like a manual, not like something a stressed dissertation student wants at midnight before a deadline.

They will tell you egen is “an elaborate wrapper for generate,” which is true. But that line does not tell a first-year student when to actually reach for it. That gap is exactly why I write these guides the way I do.

Common egen Functions You Will Actually Use

  • mean(): average of a variable across the whole dataset or a group
  • rowmean(): average across variables, calculated per row
  • total(): sum across a group or the whole dataset
  • rowtotal(): sum across variables in the same row, missing treated as zero by default
  • sd(): standard deviation for a group
  • group(): creates a numeric group identifier from one or more categorical variables
  • tag(): flags one observation per group, useful for counting unique entities

Pair any of these with bysort when you want the statistic calculated separately for each group instead of the whole dataset:

bysort region: egen avg_income = mean(income)

This creates a region specific average income for every row belonging to that region. Fixed effects vs random effects in Stata is a natural next read once you are comfortable with group-level variables like this. Once gen and egen feel comfortable, cleaning and organising your do file properly is usually the next skill worth building. Statssy’s guide to data transformation in Stata is a good next stop.

Still Stuck? When It Is Worth Getting Stata Help

Reading an explanation is one thing. Applying it correctly to your own messy, real-world dataset at 1am before a submission deadline is a different problem altogether. I say this as someone who has sat with hundreds of students staring at a red error message. Most times they are convinced their entire dataset is broken, when really it is one misplaced function.

If you are still stuck after this, that is completely normal. It is exactly the kind of thing a stata tutor online sorts out in a single session. I work with students across the UK and USA who need an online stata tutor for everything from a single stuck command to full dissertation data analysis support, and sessions are scheduled around your time zone rather than mine.

Here’s a composite example based on situations I see often. A student working on an MBA dissertation, two days from submission, has a panel dataset where her group means keep returning missing for entire regions. She had used gen with a mean() call that Stata was silently misreading.

Switching to bysort with egen fixes it within a single session, and her analysis chapter finally runs clean. I see some version of this mix up almost every submission season.

Students look for this kind of help under different names. Some search online tutor for stata, others type online tutoring for statistics or statistics tutor online. Plenty just search free statistics tutor online first, testing the waters before committing to online statistics tutoring.

Whatever the exact words, you need a real person checking your actual do file, not a generic forum answer. That is what Stata tutoring at Statssy is built for.

If Stata specifically is not even your main worry yet and you are still building basics, start with these Stata basics before jumping into group-level commands like egen. And if your struggle is really with the wider stats course rather than one command, an online statistics tutor who covers your exact syllabus is often the faster fix. That includes ap statistics tutoring online for school-level students, or general statistics tutors online for a college course. Online statistics tutoring at Statssy covers exactly that range, from Stata specific doubts to full syllabus support.

FAQ

1. What is the difference between gen and egen in Stata? gen creates variables row by row using plain expressions. egen uses a fixed set of built-in functions and can calculate statistics across rows or groups, not just within one row.

2. Why use egen instead of generate? Because egen has functions like mean(), rowmean(), total(), and group() built in, so you do not have to write that logic yourself. gen cannot use any of these; it only understands plain arithmetic expressions, which is exactly why gen mean(x) throws an error.

3. How does egen handle missing values differently than gen? Many egen functions, like rowtotal(), treat missing values as zero by default. gen does not do this automatically, so a single missing value in an expression can make the whole result missing unless you handle it yourself.

4. Can egen be used with bysort? Yes, and this is one of the most useful combinations in Stata. bysort groupvar: egen newvar = function(x) calculates the statistic separately for each group.

5. Is egen slower than gen? Generally yes, especially on large datasets, since egen often has to scan more of the data to compute its statistic. For simple row-level arithmetic, gen is faster.

6. What is the difference between egen and collapse? egen adds a new variable to your existing dataset while keeping all your original observations. collapse replaces your dataset entirely with a summarised, smaller version, one row per group.

7. What is the difference between gen and replace in Stata? gen creates a brand new variable and fails if that variable name already exists. replace overwrites the values of a variable that already exists. If you need to fix or update an existing variable, use replace, not gen.

8. Do I need a Stata tutor to understand gen and egen, or can I self teach? Most students can self teach the basics from a guide like this one. Where a tutor genuinely helps is applying it correctly to your own dataset’s specific quirks, missing data patterns, and deadline pressure. That is exactly what an online stata tutor or online tutoring stata session is for.

Written by Siddharth Gupta, statistics tutor and dissertation data analyst with 12 years of research and teaching experience. Connect on LinkedIn.

Perfect for students, researchers, and professionals looking to build real statistical skills.