count
Counts rows — all of them, or only those meeting a condition.
What we have
- all rows, or those matching an
if - the answer is left in
r(N)for a later command
Coming later
Nothing known to be missing.
How you write it
count [if]
Square brackets mean optional. A vertical bar means choose one.
What it does
count on its own is the size of the dataset. count if age >= 60 is how many people are sixty or over. It is the quickest way to check an assumption before you build anything on it.
The answer is also left behind in r(N), so a later command or a do-file can use it.
Watch out. Missing values count as larger than any number, so
count if age > 100 includes the people whose age is blank. Write count if age > 100 & !missing(age) when you do not want them. See the expressions page.Try it
Every example below was run after sysuse vira.sample02, clear.
. count if age >= 60
1,860
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)
int(mask.sum())
R
library(dplyr)
stata_missing <- function(x)
if (is.numeric(x)) ifelse(is.na(x), Inf, x) else ifelse(is.na(x), "", x)
df %>% filter((stata_missing(age) >= 60)) %>% nrow()
# This R was run in a real R (4.6.1) and gave the same numbers.