Debian Codegraph @

inst/doc/extending.Rmd

raw
1 ---
2 title: "Custom formatting"
3 output: html_vignette
4 vignette: >
5 %\VignetteIndexEntry{Custom formatting}
6 %\VignetteEngine{knitr::rmarkdown}
7 %\VignetteEncoding{UTF-8}
8 ---
9
10 ```{r, include = FALSE}
11 knitr::opts_chunk$set(
12 collapse = TRUE,
13 comment = "#>"
14 )
15 ```
16
17 ```{r setup}
18 library(pillar)
19 ```
20
21 How to customize the printed output of a `"tbl"` subclass?
22 This vignette shows the various customization options.
23 Customizing the formatting of a vector class in a tibble is described in `vignette("pillar", package = "vctrs")`.
24 An overview over the control and data flow is given in `vignette("printing")`.
25
26 This vignette assumes that the reader is familiar with S3 classes, methods, and inheritance.
27 The ["S3" chapter](https://adv-r.hadley.nz/s3.html) of Hadley Wickham's "Advanced R" is a good start.
28
29 To make use of pillar's printing capabilities, create a class that inherits from `"tbl"`, like tibble (classes `"tbl_df"` and `"tbl"`), dbplyr lazy tables (`"tbl_lazy"` and `"tbl"`) and sf spatial data frames (`"sf"`, `"tbl_df"` and `"tbl"`).
30 Because we are presenting various customization options, we create a constructor for an example data frame with arbitrary subclass.
31
32 ```{r}
33 example_tbl <- function(class = NULL) {
34 vctrs::new_data_frame(
35 list(
36 a = letters[1:3],
37 b = data.frame(c = 1:3, d = 4:6 + 0.5)
38 ),
39 class = c(class, "tbl")
40 )
41 }
42 ```
43
44 The `"default"` class doesn't have any customizations yet, and prints like a regular tibble.
45
46 ```{r}
47 example_tbl()
48 ```
49
50
51 ## Header
52
53 ### Tweak header
54
55 The easiest customization consists of tweaking the header.
56 Implement a `tbl_sum()` method to extend or replace the information shown in the header, keeping the original formatting.
57
58 ```{r}
59 tbl_sum.default_header_extend <- function(x, ...) {
60 default_header <- NextMethod()
61 c(default_header, "New" = "A new header")
62 }
63
64 example_tbl("default_header_extend")
65
66 tbl_sum.default_header_replace <- function(x, ...) {
67 c("Override" = "Replace all headers")
68 }
69
70 example_tbl("default_header_replace")
71 ```
72
73
74 ### Restyle header
75
76 To style the header in a different way, implement a `tbl_format_header()` method.
77 The implementation is responsible for the entire formatting and styling, including the leading hash.
78
79 ```{r}
80 tbl_format_header.custom_header_replace <- function(x, setup, ...) {
81 cli::style_italic(names(setup$tbl_sum), " = ", setup$tbl_sum)
82 }
83
84 example_tbl("custom_header_replace")
85 ```
86
87
88 ## Footer
89
90 ### Restyle footer
91
92 Similarly, to add information the footer, or to replace it entirely, implement a `tbl_format_footer()` method.
93 Here, as in all `tbl_format_*()` methods, you can use the information contained in the setup object, see `?new_tbl_format_setup` for the available fields.
94 Again, the implementation is responsible for the entire formatting and styling, including the leading hash if needed.
95
96 ```{r}
97 tbl_format_footer.custom_footer_extend <- function(x, setup, ...) {
98 default_footer <- NextMethod()
99
100 extra_info <- "and with extra info in the footer"
101 extra_footer <- style_subtle(paste0("# ", cli::symbol$ellipsis, " ", extra_info))
102
103 c(default_footer, extra_footer)
104 }
105
106 print(example_tbl("custom_footer_extend"), n = 2)
107
108 tbl_format_footer.custom_footer_replace <- function(x, setup, ...) {
109 paste0("The table has ", setup$rows_total, " rows in total.")
110 }
111
112 print(example_tbl("custom_footer_replace"), n = 2)
113 ```
114
115
116 ### Compute additional info beforehand
117
118 If the same information needs to be displayed in several parts (e.g., in both header and footer), it is useful to compute it in `tbl_format_setup()` and store it in the setup object.
119 New elements may be added to the setup object, existing elements should not be overwritten.
120 Exception: the `tbl_sum` element contains the output of `tbl_sum()` and can be enhanced with additional elements.
121
122 ```{r}
123 tbl_format_setup.extra_info <- function(x, width, ...) {
124 setup <- NextMethod()
125 cells <- prod(dim(x))
126 setup$cells <- cells
127 setup$tbl_sum <- c(setup$tbl_sum, "Cells" = as.character(cells))
128 setup
129 }
130
131 tbl_format_footer.extra_info <- function(x, setup, ...) {
132 paste0("The table has ", setup$cells, " cells in total.")
133 }
134
135 example_tbl("extra_info")
136 ```
137
138
139 ## Row IDs
140
141 By implementing the generic `ctl_new_rowid_pillar()`, printing of the row ID column can be customized. In order to print Roman instead of Arabic numerals, one could use `utils::as.roman()` to generate the corresponding sequence and build up a row ID pillar using `new_pillar()` and associated methods as has been introduced previously.
142
143 ```{r}
144 ctl_new_rowid_pillar.pillar_roman <- function(controller, x, width, ...) {
145 out <- NextMethod()
146 rowid <- utils::as.roman(seq_len(nrow(x)))
147 width <- max(nchar(as.character(rowid)))
148 new_pillar(
149 list(
150 title = out$title,
151 type = out$type,
152 data = pillar_component(
153 new_pillar_shaft(list(row_ids = rowid),
154 width = width,
155 class = "pillar_rif_shaft"
156 )
157 )
158 ),
159 width = width
160 )
161 }
162
163 example_tbl("pillar_roman")
164 ```
165
166
167 ## Body
168
169 ### Tweak pillar composition
170
171 Pillars consist of components, see `?new_pillar_component` for details.
172 Extend or override the `ctl_new_pillar()` method to alter the appearance.
173 The example below adds table rules of constant width to the output.
174
175 ```{r}
176 ctl_new_pillar.pillar_rule <- function(controller, x, width, ..., title = NULL) {
177 out <- NextMethod()
178 new_pillar(list(
179 top_rule = new_pillar_component(list("========"), width = 8),
180 title = out$title,
181 type = out$type,
182 mid_rule = new_pillar_component(list("--------"), width = 8),
183 data = out$data,
184 bottom_rule = new_pillar_component(list("========"), width = 8)
185 ))
186 }
187
188 example_tbl("pillar_rule")
189 ```
190
191 To make the width adaptive, we implement a `"rule"` class with a `format()` method that formats rules to prespecified widths.
192
193 ```{r}
194 rule <- function(char = "-") {
195 stopifnot(nchar(char) == 1)
196 structure(char, class = "rule")
197 }
198
199 format.rule <- function(x, width, ...) {
200 paste(rep(x, width), collapse = "")
201 }
202
203 ctl_new_pillar.pillar_rule_adaptive <- function(controller, x, width, ..., title = NULL) {
204 out <- NextMethod()
205 if (is.null(out)) {
206 return(NULL)
207 }
208
209 new_pillar(list(
210 top_rule = new_pillar_component(list(rule("=")), width = 1),
211 title = out$title,
212 type = out$type,
213 mid_rule = new_pillar_component(list(rule("-")), width = 1),
214 data = out$data,
215 bottom_rule = new_pillar_component(list(rule("=")), width = 1)
216 ))
217 }
218
219 example_tbl("pillar_rule_adaptive")
220 ```
221
222
223 ### Tweak display of compound pillars
224
225 Compound pillars are created by `ctl_new_pillar_list()` for columns that contain a data frame, a matrix or an array.
226 The default implementation also calls `ctl_new_pillar()` shown above.
227 The (somewhat artificial) example hides all data frame columns in a column with the type `"<hidden>"`.
228
229 ```{r}
230 ctl_new_pillar_list.hide_df <- function(controller, x, width, ..., title = NULL) {
231 if (!is.data.frame(x)) {
232 return(NextMethod())
233 }
234
235 if (width < 8) {
236 return(NULL)
237 }
238
239 list(new_pillar(
240 list(
241 title = pillar_component(new_pillar_title(title)),
242 type = new_pillar_component(list("<hidden>"), width = 8),
243 data = new_pillar_component(list(""), width = 1)
244 ),
245 width = 8
246 ))
247 }
248
249 example_tbl("hide_df")
250 ```
251
252
253 ### Restyle body
254
255 Last but not least, it is also possible to completely alter the display of the body by overriding `tbl_format_body()`.
256 The example below uses plain data frame output for a tibble.
257
258 ```{r}
259 tbl_format_body.oldskool <- function(x, setup, ...) {
260 capture.output(print.data.frame(setup$df))
261 }
262
263 print(example_tbl("oldskool"), n = 2)
264 ```
265
266 Note that default printed output is computed in `tbl_format_setup()`, this takes a considerable amount of time.
267 If you really need to change the output for the entire body, consider providing your own `tbl_format_setup()` method.