Virata manual

tabulate

Counts how many rows fall in each category, or in each pair of categories.

What we have

  • one-way and two-way tables
  • row, column, chi2, nofreq and nolabel
  • summarize(), for the mean of another variable in each cell
  • frequency weights

Coming later

  • tab1 and tab2, for several tables in one command
  • the chi-squared statistic is not printed while set mincell is on, because it can be worked backwards to the hidden counts

You may shorten it to tab.

How you write it

tabulate var1 [var2] [if] [weight] [, row column nofreq chi2]

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

What it does

One variable gives a frequency table: each value, how many rows have it, and what share of the whole that is. Two variables give a cross-tabulation — a grid of counts — with a test of whether the two are related (a chi-squared test) if you ask for it.

row and column turn the counts into percentages across or down; nofreq drops the counts and leaves only the percentages.

Watch out. With set mincell switched on, cells with very few people are hidden, and the chi-squared statistic is not printed at all — because it can be worked backwards to recover the hidden counts. See set mincell.

Try it

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

. tabulate sector
      sector |       Freq.     Percent        Cum.
-------------+------------------------------------
       Rural |       3,987       66.45       66.45
       Urban |       2,013       33.55      100.00
-------------+------------------------------------
       Total |       6,000      100.00            
The same thing in pandas and in R

pandas

df["sector"].value_counts().sort_index()

R

library(dplyr)
df %>% count(sector) %>% mutate(percent = 100 * n / sum(n))

# This R was run in a real R (4.6.1) and gave the same numbers.
. tabulate state sector, row
              sector
       state |     Rural     Urban |     Total
-------------+---------------------+----------
       Bihar |       519       187 |       706
             |     73.51     26.49 |    100.00
     Gujarat |       676       315 |       991
             |     68.21     31.79 |    100.00
      Kerala |       671       360 |     1,031
             |     65.08     34.92 |    100.00
      Odisha |       731       501 |     1,232
             |     59.33     40.67 |    100.00
      Punjab |       678       389 |     1,067
             |     63.54     36.46 |    100.00
   Rajasthan |       712       261 |       973
             |     73.18     26.82 |    100.00
-------------+---------------------+----------
       Total |     3,987     2,013 |     6,000
The same thing in pandas and in R

pandas

import pandas as pd

pd.crosstab(df["state"], df["sector"])

R

library(dplyr)
counts <- table(df$state, df$sector)
counts

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

Nearby

summarize tabstat correlate pwcorr ttest mean