% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/color_table.R
\name{color_table}
\alias{color_table}
\alias{color_table.table}
\alias{color_table.ftable}
\alias{color_table.structable}
\alias{color_table.data.frame}
\alias{color_table.matrix}
\alias{color_table.default}
\title{Smart Display of Frequency Tables with Colored Cell Backgrounds}
\usage{
color_table(x, ...)

\method{color_table}{table}(
  x,
  formula = NULL,
  values = c("freq", "residuals"),
  shade = c("residuals", "freq", "pearson", "deviance"),
  model = NULL,
  expected = NULL,
  palette = NULL,
  legend = FALSE,
  margins = TRUE,
  digits = 0,
  title = NULL,
  filename = NULL,
  ...
)

\method{color_table}{ftable}(
  x,
  values = c("freq", "residuals"),
  shade = c("residuals", "freq", "pearson", "deviance"),
  model = NULL,
  expected = NULL,
  palette = NULL,
  legend = FALSE,
  margins = TRUE,
  digits = 0,
  title = NULL,
  filename = NULL,
  ...
)

\method{color_table}{structable}(
  x,
  values = c("freq", "residuals"),
  shade = c("residuals", "freq", "pearson", "deviance"),
  model = NULL,
  expected = NULL,
  palette = NULL,
  legend = FALSE,
  margins = TRUE,
  digits = 0,
  title = NULL,
  filename = NULL,
  ...
)

\method{color_table}{data.frame}(
  x,
  formula = NULL,
  freq_col = NULL,
  values = c("freq", "residuals"),
  shade = c("residuals", "freq", "pearson", "deviance"),
  model = NULL,
  expected = NULL,
  palette = NULL,
  legend = FALSE,
  margins = TRUE,
  digits = 0,
  title = NULL,
  filename = NULL,
  ...
)

\method{color_table}{matrix}(
  x,
  values = c("freq", "residuals"),
  shade = c("residuals", "freq", "pearson", "deviance"),
  model = NULL,
  expected = NULL,
  palette = NULL,
  legend = FALSE,
  margins = TRUE,
  digits = 0,
  title = NULL,
  filename = NULL,
  ...
)

\method{color_table}{default}(x, ...)
}
\arguments{
\item{x}{A \code{"table"}, \code{"xtabs"}, \code{"matrix"}, \code{"ftable"}, \code{"structable"}, or \code{"data.frame"} object}

\item{...}{Additional arguments passed to methods}

\item{formula}{Formula specifying a \code{col_vars ~ row_vars} layout (for multi-way tables) to
make them "flat" as defined for \code{vcd::structable()} and \code{stats::ftable()}.}

\item{values}{What values to display in cells: \code{"freq"} for observed frequencies (default),
or \code{"residuals"} to display the residual values. When \code{values = "residuals"}, margins
are suppressed since residuals don't have meaningful totals.}

\item{shade}{What values determine cell shading: \code{"residuals"} (default), \code{"freq"},
\code{"pearson"}, or \code{"deviance"}}

\item{model}{A fitted model (loglm or glm) to compute residuals from.
If NULL and shade involves residuals, uses an independence model for all factors.}

\item{expected}{Expected frequencies (alternative to \code{model}), a data structure of the same shape
as \code{x}}

\item{palette}{Color palette function or vector for background colors. Default depends on shade
type. When \code{shade = "freq"} the default is \code{palette = c("white", "firebrick")}; otherwise
\code{c("#B2182B", "white", , "#2166AC")} ranging from red to blue for negative and positive
residuals. The background colors are computed by interpolation using
\code{scales::col_numeric()}.}

\item{legend}{Controls display of shading interpretation note:
\code{TRUE} or \code{"note"} (default) adds a source note explaining the shading;
\code{FALSE} (default) suppresses the note, but a message is printed in the console.}

\item{margins}{Logical, include row/column totals?}

\item{digits}{Number of decimal places for displayed values}

\item{title}{Optional table title}

\item{filename}{Optional filename to save the table as an image. If provided,
the table is saved using \code{\link[gt]{gtsave}}. Supported formats include
\code{.png}, \code{.pdf}, \code{.html}, \code{.rtf}, and \code{.docx}.
The file format is determined by the file extension. Other arguments can be passed
to \code{\link[gt]{gtsave}} via \code{...}.}

\item{freq_col}{Name of the frequency column. If NULL, looks for "Freq" or "count".}
}
\value{
A gt table object that can be further customized
}
\description{
\code{color_table()} creates a formatted, semi-graphic "heatmap" table display of frequency data with cell backgrounds
colored according to observed frequencies or their residuals from a loglinear model. The goal is to provide a
"smart" tabular display of cross-classified frequency data, with some abilities to highlight possibly interesting
patterns or unusual cells.
This is an S3 generic function, providing methods for different input types: \code{"table"}, \code{"xtabs"}, \code{"matrix"}, \code{"ftable"}, \code{"structable"} or \code{"data.frame"}.
}
\details{
This function provides a heatmap-style representation of a frequency table,
where background coloring is used to visualize patterns and anomalies in the data.
When shading by \emph{residuals} (the default), cells with large positive residuals
(more observations than expected) are shaded red, while cells with large negative
residuals (fewer than expected) are shaded blue. This makes it easy to identify
cells that deviate substantially from what would be expected under a given model
(by default, the independence model).

For multi-way tables (3 or more dimensions), residuals are computed from the
model of complete independence among all factors using \code{\link[MASS]{loglm}}.
But you can specify a model using the \code{model} or \code{expected} arguments, in a way similar to that provided
by \code{mosaic.glm()}.
A message is printed showing the chi-squared statistic, degrees of freedom,
and p-value for this test.

\strong{Multi-variable row and column labels}

\code{formula} follows the \code{col_vars ~ row_vars} convention used by
\code{\link[vcd:structable]{vcd::structable()}} and \code{\link[stats:ftable]{stats::ftable()}} (confirmed to agree between the
two across many row/col splits of \code{HairEyeColor} and \code{Titanic} -- see
\code{dev/color_table/formula-row-col-comparison.R}). When \code{formula} specifies
more than one variable on either side, \code{color_table()} avoids concatenated
labels like \code{"Black_Male"}. Multiple column variables (on the left of \code{~},
e.g. \code{formula = Class + Sex + Age ~ Survived}) are shown using
\code{\link[gt:tab_spanner]{gt::tab_spanner()}} headings that group columns under their outer
variable(s). Multiple row variables (on the right of \code{~}, e.g.
\code{formula = Survived ~ Class + Sex}) are shown as separate stub columns, one
per row variable, using \code{gt}'s multi-column stub support (\code{rowname_col}
accepting a vector of column names), with repeated values left blank. The
two can be combined in the same table.

\strong{Contrast shading}

For cells with dark background colors, black text can be difficult to read.
This function automatically selects white or black text for each cell based
on which provides better contrast against the background color. If the
\pkg{colorspace} package is available, \code{\link[colorspace]{contrast_ratio}}
is used to determine the optimal text color according to WCAG 2.1 guidelines.
Otherwise, a fallback based on relative luminance (ITU-R BT.709) is used.

\strong{Use in documents}

In R Markdown (\code{.Rmd}) or Quarto (\code{.qmd}) documents, \pkg{gt} tables
render natively in \strong{HTML output} — simply return the \code{gt} object from
a chunk and knitr renders it automatically via \pkg{gt}'s built-in
\code{knit_print} method. No \code{filename} argument is needed.

For \strong{PDF or Word output}, \pkg{gt} does not render natively. Use the
\code{filename} argument to save the table as a \code{.png} image, then include
it with \code{\link[knitr]{include_graphics}}:

\preformatted{
    color_table(my_table, filename = "my_table.png")
    knitr::include_graphics("my_table.png")
}

The \code{vwidth} and \code{vheight} arguments (passed via \code{...}) control
the image viewport size in pixels.  Supported save formats are
\code{.png}, \code{.pdf}, \code{.html}, \code{.rtf}, and \code{.docx}.

For documents that target \strong{multiple output formats}, a small helper that
branches on \code{\link[knitr]{is_html_output}} avoids duplicating code:

\preformatted{
    gt_obj <- color_table(my_table)
    if (knitr::is_html_output()) {
      gt_obj
    } else {
      gt::gtsave(gt_obj, "my_table.png")
      knitr::include_graphics("my_table.png")
    }
}

If you need a caption or cross-reference label, use \code{gt::tab_caption()}
on the returned object:
\preformatted{
    color_table(my_table) |>
      gt::tab_caption("Table 1: Pattern of association in MyTable")
}
}
\section{Methods (by class)}{
\itemize{
\item \code{color_table(table)}: Method for table objects (including result of xtabs)

\item \code{color_table(ftable)}: Method for ftable objects

\item \code{color_table(structable)}: Method for structable objects (vcd package)

\item \code{color_table(data.frame)}: Method for data.frame in frequency form

\item \code{color_table(matrix)}: Method for matrix objects

\item \code{color_table(default)}: Default method

}}
\examples{
# Basic usage with 2-way table - shade by residuals from independence
data(HairEyeColor)
HEC <- margin.table(HairEyeColor, 1:2)  # 2-way: Hair x Eye
color_table(HEC)

# Shade by frequencies instead (no message printed)
color_table(HEC, shade = "freq")

# 3-way table - using a formula to specify layout (col_vars ~ row_vars):
# Eye is the single column variable, Hair and Sex are row variables shown
# as separate stub columns
color_table(HairEyeColor, formula = Eye ~ Hair + Sex)

# Display residual values in cells instead of frequencies
color_table(HEC, values = "residuals")

# Multiple column variables - shown using nested spanner headings instead
# of concatenated column labels
data(Titanic)
color_table(Titanic, formula = Class + Sex ~ Survived)

# Multiple row AND column variables together: column spanners (Class, Sex)
# combined with row-variable stub columns (Age, Survived)
color_table(Titanic, formula = Class + Sex ~ Age + Survived, legend = TRUE)

\dontrun{
# From a data.frame in frequency form (2-way)
hec_df <- as.data.frame(HEC)
color_table(hec_df)

# Save table as an image file
color_table(HEC, filename = "hair_eye_table.png")
}

}
