Search code examples
rxtable

Include dimension names in row and column headers for LaTeX-formatted contingency table


If the categories of the attributes in a contingency table are mere numbers, using only these numbers as column/row header is not enough -- a description what the numbers mean is called for. The picture below shows the cross-classification of household size vs. number of foreigners in a household sample:

Example table

Does anyone have experience in producing such tables using R+LaTeX?


Solution

  • There's ftable that turns a contingency table into a two-dimensional formatted table and allows specifying what is shown in rows and what in columns (also useful for tables of more than two dimensions). The memisc package helps turning this into nice LaTeX:

    library(magrittr)
    library(memisc)
    expand.grid(Foreigners = 0:5, `Total persons` = 1:8) %>%
      cbind(Freq = rnorm(6*8, 20, 10)) %>%
      xtabs(formula = Freq~.) %>%
      ftable %>%
      toLatex
    

    No hacking needed, and LaTeX can be used for the names of the columns in expand.grid (to support e.g. rotation and/or spanning multiple rows). The generated LaTeX code requires the booktabs and dcolumn packages.

    Compiled output

    Related: Creating a latex table from ftable object in R.