anthe.sevenants

How to build a cross table in R

2023-01-31

I keep forgetting how to easily build a cross table in R, so here is how, for future reference:

xtabs(~ order + component, df)
  • order: the rows of your cross table
  • component: the columns of your cross table
  • df: the dataframe containing your data

Example output:

       component
order   WR-P-E-A WR-P-E-C WR-P-E-F WR-P-E-G WR-P-E-H WR-P-E-I WR-P-E-J WR-P-E-K WR-P-E-L WR-P-P-B WR-P-P-C WR-P-P-D WR-P-P-E WR-P-P-F WR-P-P-G WR-P-P-H
  green    21561      880       16      115      139      216     2587       31     3964    10126      138        2       15      265    36659    13992
  red      19124     1332       40       58      105      274     4805       15     5052    29468      193        6      133     2167    72653    22803
       component
order   WR-P-P-I WR-P-P-J WR-P-P-K WR-U-E-A WR-U-E-E
  green     1957       39      318     1843       88
  red       5605      199     1112      913       72