Virata manual

preserve

Takes a snapshot of the data so you can get it back.

What we have

  • a snapshot of the data, held in memory

Coming later

Nothing known to be missing.

How you write it

preserve

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

What it does

For when you want to do something destructive — drop most of the rows, keep one group, collapse to averages — and then carry on with the full dataset. preserve, do the damage, restore.

This is the safety net that makes the rest of the editing commands comfortable to use.

Watch out. The snapshot lives in memory and only one is held at a time.

Try it

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

. preserve
The same thing in pandas and in R

R

# no R form for `preserve` yet -- see docs/r-equivalents.md
. keep if age > 60
(4,238 observations deleted)
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["age"]) > 60)
df = df[mask].reset_index(drop=True)

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 %>% filter((stata_missing(age) > 60))

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

R

# no R form for `restore` yet -- see docs/r-equivalents.md

Nearby

generate replace egen recode rename order