Virata manual

replace

Changes values in a column you already have.

What we have

  • the same expressions as generate, with if and in
  • a single dot for missing on the right-hand side

Coming later

Nothing known to be missing.

How you write it

replace var = expression [if] [in]

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

What it does

The same arithmetic as generate, but pointed at an existing column. Nearly always used with a condition: replace mpce = . if mpce < 0 blanks out the impossible values rather than the whole column.

A single dot . is how you write "missing" on the right-hand side.

Watch out. There is no undo. preserve before a run of replace commands and restore puts the data back if it went wrong.

Try it

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

. replace mpce = 0 if mpce < 0
(0 real changes made)
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

mask = (stata_missing(df["mpce"]) < 0)
df.loc[mask, "mpce"] = 0

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(mpce = ifelse((stata_missing(mpce) < 0), 0, mpce))

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

Nearby

generate egen recode rename order drop