Skip to content

Commit 9819bc7

Browse files
committed
work on color_table, knit_include, ...
1 parent d0a461e commit 9819bc7

9 files changed

Lines changed: 136 additions & 90 deletions

File tree

NEWS.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
## Version 0.9.3
22

3-
* Added tidy conversion functions: as_array(), as_caseform(), as_freqform, as_table() PR #22 [Thx: Gavin Klorfine]
3+
* Added tidy conversion functions: `as_array()`, `as_caseform()`, `as_freqform`, `as_table()` PR #22 [Thx: Gavin Klorfine]
44
* Fixed bug in `mcaplot()` coming from `ca::cacoords(): "non-conformable arguments"
55

66
## Version 0.9.2

R/Crossings.R

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44
#' `Crossings` creates an n-1 column matrix corresponding to different
55
#' degrees of difficulty in crossing from one level to the next, as described
66
#' by Goodman (1972).
7-
#'
8-
#' Instead of treating all mobility as equal, this model posits that the difficulty
9-
#' of moving between categories increases with the number of boundaries (or "crossings")
10-
#' that must be crossed, and that associations between categories decrease
7+
#'
8+
#' Instead of treating all mobility as equal, this model posits that the difficulty
9+
#' of moving between categories increases with the number of boundaries (or "crossings")
10+
#' that must be crossed, and that associations between categories decrease
1111
#' with their separation.
1212
#'
1313
#'
@@ -45,11 +45,11 @@
4545
#' hauser.CRdiag <- update(hauser.indep,
4646
#' ~ . + Crossings(Father,Son) + Diag(Father,Son))
4747
#' LRstats(hauser.CRdiag)
48-
#'
48+
#'
4949
#' # what does Crossings do?
50-
#' cr <-with(Hauser79, Crossings(Father, Son))
50+
#' cr <- with(Hauser79, Crossings(Father, Son))
5151
#' head(cr)
52-
#' Crossings levels
52+
#' # Show the codings for varying Crossings levels
5353
#' matrix(cr[,1], nrow=5)
5454
#' matrix(cr[,2], nrow=5)
5555
#' matrix(cr[,3], nrow=5)

R/color_table.R

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,31 +50,34 @@
5050
# is confusing and ugly. Examples:
5151
# color_table(PreSex, formula = MaritalStatus + Gender ~ PremaritalSex + ExtramaritalSex)
5252
# color_table(PreSex, formula = Gender + PremaritalSex + ExtramaritalSex ~ MaritalStatus)
53-
# This can e handled using column spanners: https://gt.rstudio.com/reference/tab_spanner.html
54-
#
53+
# This can be handled using column spanners: https://gt.rstudio.com/reference/tab_spanner.html
54+
#
5555

5656

57-
#' Display Frequency Table with Colored Cell Backgrounds
57+
#' Smart Display of Frequency Table with Colored Cell Backgrounds
5858
#'
59-
#' Creates a formatted, semi-graphic "heatmap" table display of frequency data with cell backgrounds
60-
#' colored according to observed frequencies or their residuals from a loglinear model.
61-
#' This is an S3 generic function with methods for different input types.
59+
#' `color_table()` creates a formatted, semi-graphic "heatmap" table display of frequency data with cell backgrounds
60+
#' colored according to observed frequencies or their residuals from a loglinear model. The goal is to provide a
61+
#' "smart" tabular display of cross-classified frequency data, with some abilities to highlight possibly interesting
62+
#' patterns or unusual cells.
63+
#' This is an S3 generic function, providing methods for different input types: `"table"`, `"xtabs"`, `"matrix"`, `"ftable"`, `"structable"` or `"data.frame"`.
6264
#'
6365
#' @param x A `"table"`, `"xtabs"`, `"matrix"`, `"ftable"`, `"structable"`, or `"data.frame"` object
6466
#' @param ... Additional arguments passed to methods
6567
#'
6668
#' @details
6769
#' This function provides a heatmap-style representation of a frequency table,
6870
#' where background coloring is used to visualize patterns and anomalies in the data.
69-
#' When shading by residuals (the default), cells with large positive residuals
71+
#' When shading by _residuals_ (the default), cells with large positive residuals
7072
#' (more observations than expected) are shaded red, while cells with large negative
7173
#' residuals (fewer than expected) are shaded blue. This makes it easy to identify
7274
#' cells that deviate substantially from what would be expected under a given model
7375
#' (by default, the independence model).
7476
#'
7577
#' For multi-way tables (3 or more dimensions), residuals are computed from the
76-
#' model of complete independence among all factors using \code{\link[MASS]{loglm}},
77-
#' unless you specify a model using the `model` or `expected` arguments.
78+
#' model of complete independence among all factors using \code{\link[MASS]{loglm}}.
79+
#' But you can specify a model using the `model` or `expected` arguments, in a way similar to that provided
80+
#' by `mosaic.glm()`.
7881
#' A message is printed showing the chi-squared statistic, degrees of freedom,
7982
#' and p-value for this test.
8083
#'

R/knit_include.R

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
11
#' Include an HTML-renderable object in any knitr output format
22
#'
3-
#' A pipe-friendly helper for objects that render natively in HTML output
4-
#' (RStudio Viewer, HTML documents) but need an image fallback for PDF, Word,
5-
#' and other non-HTML formats.
3+
#' A pipe-friendly helper in Rmarkdown, Quarto, and other documents for objects that render natively in HTML output
4+
#' (RStudio Viewer, HTML documents) but need a convenient image fallback for PDF, Word,
5+
#' and other non-HTML formats. It was designed to solve a problem in rendering the result of `color_table()`,
6+
#' and then generalized to provide for other similar cases.
67
#'
7-
#' Supported classes:
8-
#' - `gt_tbl` (gt package) -- saved via \code{\link[gt]{gtsave}}
9-
#' - `htmlwidget` (htmlwidgets family: plotly, DT, leaflet, dygraphs, ...)
8+
#' Supported classes (handled internally) solve this problem by saving the image to a file and then inserting it in the document
9+
#' using `knitr::include_graphics()`:
10+
#' - `"gt_tbl"` (gt package) -- saved via \code{\link[gt]{gtsave}}
11+
#' - `"htmlwidget"` (htmlwidgets family: plotly, DT, leaflet, dygraphs, ...)
1012
#' -- saved via
1113
#' \code{\link[htmlwidgets]{saveWidget}}
1214
#' + \code{\link[webshot2]{webshot}}
1315
#'
14-
#' Packages that handle cross-format output natively (flextable, kableExtra,
15-
#' huxtable) do NOT need this helper.
16+
#' Packages that handle cross-format output natively (\pkg{flextable}, \pkg{kableExtra},
17+
#' \pkg{huxtable}) do NOT need this helper.
1618
#'
1719
#' For any other class, \code{x} is returned as-is in all output formats and
1820
#' knitr's normal printing applies. This means the function is safe to use in
19-
#' a pipe on any object: it only intervenes when it knows how to help.
21+
#' a pipe on any object: it only intervenes when it knows how to help!
2022
#'
2123
#' @param x Any R object. Specialised handling for \code{gt_tbl} and
2224
#' \code{htmlwidget}; all other classes are passed through

dev/test-pairs-diag.R

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# test diag pairs with cell labels
2+
#
3+
library(vcdExtra)
4+
Hoyt <- vcdExtra::Hoyt
5+
Hoyt2 <- collapse.table(Hoyt,
6+
Status = c("College", rep("Non-College", 3)),
7+
Occupation = c(rep("High", 3),
8+
rep("Medium", 2),
9+
rep("Low", 3)))
10+
11+
pairs(
12+
Hoyt2,
13+
gp = shading_Friendly,
14+
space = 0.4,
15+
gp_args = list(interpolate = 1:4),
16+
diag_panel_args = list(NULL)
17+
)

man/Crossings.Rd

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

man/color_table.Rd

Lines changed: 10 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

man/knit_include.Rd

Lines changed: 11 additions & 9 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

vignettes/articles/color_table.Rmd

Lines changed: 65 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,33 @@ library(vcdExtra)
2121
## Overview
2222

2323
`color_table()` produces a `gt` table object with cell backgrounds shaded by
24-
observed frequencies or Pearson residuals from an independence model.
25-
26-
`gt` tables render natively in **HTML output** — just return the object from a
27-
chunk and knitr handles the rest via `gt`'s built-in `knit_print` method.
28-
For **PDF or Word output**, save the table as a `.png` image and include it with
29-
`knitr::include_graphics()` (see [PDF / Word output] below).
24+
observed frequencies or Pearson residuals from an independence (or user-supplied)
25+
model. The goal is a "smart" tabular display that makes patterns of association
26+
or unusual cells immediately visible.
27+
28+
When used interactively in RStudio, the returned `gt` object renders directly
29+
in the **Viewer** panel — no extra steps needed. However, using `color_table()`
30+
in R Markdown (`.Rmd`) or Quarto (`.qmd`) documents requires some special
31+
consideration because `gt` tables render natively only in **HTML output**. For
32+
**PDF or Word output**, the table must be saved as a PNG image and included with
33+
`knitr::include_graphics()`.
34+
35+
The `knit_include()` helper in this package handles that branching automatically.
36+
Piping a `gt` table through `knit_include()` returns it unchanged for HTML output,
37+
and saves a PNG fallback for all other formats — so the same chunk knits correctly
38+
regardless of the output format.
3039

3140
---
3241

3342
## HTML output — return the gt object directly
3443

35-
No `filename` argument is needed for HTML output.
44+
For documents that are compiled to HTML, `color_table()` renders natively: just return the object
45+
from a chunk and `knitr` handles it via `gt`'s built-in `knitr::knit_print()` method.
46+
No `filename` argument or extra wrapper is needed.
47+
48+
The first example shades cells by Pearson residuals from the independence model
49+
(the default), making over- and under-represented Hair×Eye combinations
50+
immediately visible.
3651

3752
```{r html-basic}
3853
data(HairEyeColor)
@@ -41,10 +56,18 @@ HEC <- margin.table(HairEyeColor, 1:2) # collapse over Sex
4156
color_table(HEC, title = "Hair \u00d7 Eye Color (residual shading)")
4257
```
4358

59+
For comparison, shading by raw frequencies (rather than residuals) gives a
60+
different picture — it highlights which combinations are simply most common,
61+
not which ones deviate from independence.
62+
4463
```{r html-freq}
4564
color_table(HEC, shade = "freq", title = "Hair \u00d7 Eye Color (frequency shading)")
4665
```
4766

67+
For a three-way table, a `formula` argument controls the layout: variables on
68+
the left of `~` become row groups, those on the right become column spanners.
69+
The legend note reproduces the chi-squared summary printed to the console.
70+
4871
```{r html-3way}
4972
color_table(HairEyeColor,
5073
formula = Eye ~ Hair + Sex,
@@ -61,8 +84,8 @@ For non-HTML output, save the table as a PNG and include with
6184
`.rtf`, `.docx`. The `vwidth` and `vheight` arguments control the image
6285
viewport in pixels.
6386

64-
The chunk below is shown for illustration (`eval=FALSE`); the HTML approach
65-
above is all that is needed when knitting to HTML.
87+
The chunk below is shown for illustration only (`eval=FALSE`); the HTML approach
88+
above is sufficient when knitting to HTML.
6689

6790
```{r pdf-basic, eval=FALSE}
6891
color_table(HEC,
@@ -76,57 +99,53 @@ knitr::include_graphics("color_table_hec.png")
7699

77100
---
78101

79-
## Universal helper — works in any output format
80-
81-
This small wrapper branches on `knitr::is_html_output()` so the same source
82-
knits correctly to HTML, PDF, or Word without changes.
83-
84-
```{r helper}
85-
include_color_table <- function(x, ..., file = "color_table_tmp",
86-
width = 600, height = 400) {
87-
gt_obj <- color_table(x, ...)
88-
if (knitr::is_html_output()) {
89-
gt_obj
90-
} else {
91-
img <- paste0(file, ".png")
92-
gt::gtsave(gt_obj, filename = img, vwidth = width, vheight = height)
93-
knitr::include_graphics(img)
94-
}
95-
}
96-
```
102+
## Universal output — `knit_include()`
103+
104+
`knit_include()` eliminates the need to branch on output format by hand.
105+
Pipe the `gt` object through it and the same chunk works correctly whether
106+
you are knitting to HTML, PDF, or Word.
97107

98108
```{r universal-demo}
99-
include_color_table(HEC,
100-
title = "Hair \u00d7 Eye Color",
101-
file = "color_table_universal",
102-
width = 520,
103-
height = 300)
109+
color_table(HEC,
110+
title = "Hair \u00d7 Eye Color") |>
111+
knit_include(width = 520, height = 300)
104112
```
105113

114+
`knit_include()` also handles `htmlwidget` objects (plotly, DT, leaflet, …)
115+
the same way — HTML output gets the interactive widget, PDF/Word output gets
116+
a screenshot. Any other class is passed through unchanged, so it is safe to
117+
use in a pipe on any object.
118+
106119
---
107120

108121
## More examples
109122

110-
### Display residual values in cells
123+
### Displaying residual values in cells
124+
125+
Setting `values = "residuals"` replaces the cell frequencies with the
126+
Pearson residual values themselves. This is useful when the exact magnitude
127+
of each deviation matters, not just its direction. Row and column totals are
128+
suppressed automatically because residuals do not have meaningful marginal sums.
111129

112130
```{r residuals-display}
113-
include_color_table(HEC,
114-
values = "residuals",
115-
title = "Hair \u00d7 Eye \u2014 Pearson residuals",
116-
file = "color_table_resid",
117-
width = 520,
118-
height = 280)
131+
color_table(HEC,
132+
values = "residuals",
133+
title = "Hair \u00d7 Eye \u2014 Pearson residuals") |>
134+
knit_include(width = 520, height = 280)
119135
```
120136

121137
### Multi-way table: PreSex data
122138

139+
The `PreSex` data cross-classifies four variables. Here `MaritalStatus` is
140+
placed on rows and the two sexual-attitude variables form nested column spanners,
141+
making the interaction structure easy to read. The legend note records the
142+
goodness-of-fit for the complete-independence model.
143+
123144
```{r presex}
124145
data(PreSex, package = "vcd")
125-
include_color_table(PreSex,
126-
formula = MaritalStatus ~ PremaritalSex + ExtramaritalSex,
127-
legend = TRUE,
128-
title = "Pre/Extra-marital Sex by Marital Status",
129-
file = "color_table_presex",
130-
width = 520,
131-
height = 300)
146+
color_table(PreSex,
147+
formula = MaritalStatus ~ PremaritalSex + ExtramaritalSex,
148+
legend = TRUE,
149+
title = "Pre/Extra-marital Sex by Marital Status") |>
150+
knit_include(width = 520, height = 300)
132151
```

0 commit comments

Comments
 (0)