Virata manual

drop

Removes columns, or removes rows.

What we have

  • dropping variables, and dropping rows with if

Coming later

Nothing known to be missing.

How you write it

drop varlist   |   drop if condition

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

What it does

Two jobs decided by what follows. drop education removes that column. drop if age < 15 removes those rows. The word if is the difference, so read it twice before pressing enter.

Watch out. Missing values are treated as larger than any number, so drop if age > 60 also drops everyone whose age is blank. Add & !missing(age) when that is not what you want.

Try it

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

. drop if age < 15
(0 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"]) < 15)
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) < 15)))

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

pandas

df = df.drop(columns=['education'])

R

library(dplyr)
df <- df %>% select(-c(education))

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

Nearby

generate replace egen recode rename order