Virata manual

generate

Adds a new column, worked out from the ones you already have.

What we have

  • the full expression language, with Stata's missing-value rule
  • if and in, and a storage type such as double
  • _n and _N, which follow the groups under bysort
  • text functions: strlen, substr, upper, lower, real, string
  • Excel's SUMIFS family, following Excel's rules — see expressions

Coming later

  • runiform() and the other random-number functions
  • format — there is no way to set how a number prints

You may shorten it to g.

How you write it

generate [type] newvar = expression [if] [in]

Square brackets mean optional. A vertical bar means choose one.

What it does

generate lnmpce = ln(mpce) makes a new column from an old one. generate rich = mpce > 4000 makes a column of 1s and 0s — 1 where the condition holds. Add if and only the rows that match get a value; the rest are left blank.

Two special quantities are available anywhere: _n is the row number and _N is the number of rows. Under bysort they change meaning usefully — _n becomes the position within the group and _N the size of the group — which is how you number people within a household.

Watch out. generate refuses to write over a column that already exists. That is on purpose; replace is the command that says you meant it.

Try it

Every example below was run after sysuse vira.sample02, clear.

. generate double lnmpce = ln(mpce)
The same thing in pandas and in R

pandas

import numpy as np

df["lnmpce"] = np.log(df["mpce"])

R

library(dplyr)
df <- df %>% mutate(lnmpce = log(mpce))

# This R was run in a real R (4.6.1) and gave the same numbers.
. generate rich = mpce > 4000
The same thing in pandas and in R

pandas

import numpy as np
import pandas as pd

def stata_missing(value):
    """Stata counts a missing value as larger than any number."""
    if isinstance(value, pd.Series):
        if pd.api.types.is_numeric_dtype(value):
            return value.astype("float64").fillna(np.inf)
        return value.fillna("")
    if value is None or (isinstance(value, float) and np.isnan(value)):
        return np.inf
    return value

df["rich"] = (stata_missing(df["mpce"]) > 4000)

R

library(dplyr)
stata_missing <- function(x)
    if (is.numeric(x)) ifelse(is.na(x), Inf, x) else ifelse(is.na(x), "", x)
df <- df %>% mutate(rich = (stata_missing(mpce) > 4000))

# This R was run in a real R (4.6.1) and gave the same numbers.

Nearby

replace egen recode rename order drop