Virata manual

keep

The opposite of drop: keeps only what you name and removes the rest.

What we have

  • keeping variables, and keeping rows with if

Coming later

Nothing known to be missing.

How you write it

keep varlist   |   keep if condition

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

What it does

keep id state mpce throws away every other column. keep if sector == 1 throws away every other row.

Usually safer to read than drop, because what survives is written down in front of you rather than inferred.

Try it

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

. keep if sector == 1
(2,013 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["sector"]) == 1)
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(sector) == 1))

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

Nearby

generate replace egen recode rename order