Debian Codegraph @

vignettes/knit_print.Rmd

raw
1 ---
2 title: "Custom Print Methods"
3 author: "Yihui Xie"
4 date: '`r Sys.Date()`'
5 output:
6 html:
7 options:
8 toc: true
9 meta:
10 css: ["@default"]
11 vignette: >
12 %\VignetteEngine{knitr::knitr_notangle}
13 %\VignetteIndexEntry{Custom Print Methods}
14 ---
15
16 Before **knitr** v1.6, printing objects in R code chunks basically emulates the
17 R console. For example, a data frame is printed like this[^1]:
18
19 [^1]: Note R prints an object without an explicit `print()` call when it is
20 *visible*; see `?invisible`
21
22 ```{r normal-print, comment=''}
23 head(mtcars)
24 ```
25
26 The text representation of the data frame above may look very familiar with most
27 R users, but for reporting purposes, it may not be satisfactory -- often times
28 we want to see a table representation instead. That is the problem that the
29 chunk option `render` and the S3 generic function `knit_print()` try to solve.
30
31 ## Customize Printing
32
33 After we evaluate each R expression in a code chunk, there is an object
34 returned. For example, `1 + 1` returns `2`. This object is passed to the chunk
35 option `render`, which is a function with two arguments, `x` and `options`, or
36 `x` and `...`. The default value for the `render` option is `knit_print`, an S3
37 function in **knitr**:
38
39 ```{r}
40 library(knitr)
41 knit_print # an S3 generic function
42 methods(knit_print)
43 getS3method('knit_print', 'default') # the default method
44 normal_print
45 ```
46
47 As we can see, `knit_print()` has a `default` method, which is basically
48 `print()` or `show()`, depending on whether the object is an S4 object. This
49 means it does nothing special when printing R objects:
50
51 ```{r collapse=TRUE}
52 knit_print(1:10)
53 knit_print(head(mtcars))
54 ```
55
56 S3 generic functions are extensible in the sense that we can define custom
57 methods for them. A method `knit_print.foo()` will be applied to the object that
58 has the class `foo`. Here is quick example of how we can print data frames as
59 tables:
60
61 ```{r}
62 library(knitr)
63 # define a method for objects of the class data.frame
64 knit_print.data.frame = function(x, ...) {
65 res = paste(c('', '', kable(x)), collapse = '\n')
66 asis_output(res)
67 }
68 # register the method
69 registerS3method("knit_print", "data.frame", knit_print.data.frame)
70 ```
71
72 If you define a method in a code chunk in a **knitr** document, the call to
73 `registerS3method()` will be necessary for R \>= 3.5.0, because the S3 dispatch
74 mechanism has changed since R 3.5.0. If you are developing an R package, see the
75 section [For package authors] below.
76
77 We expect the print method to return a character vector, or an object that can
78 be coerced into a character vector. In the example above, the `kable()` function
79 returns a character vector, which we pass to the `asis_output()` function so
80 that later **knitr** knows that this result needs no special treatment (just
81 write it as is), otherwise it depends on the chunk option `results` (`= 'asis'`
82 / `'markup'` / `'hide'`) how a normal character vector should be written. The
83 function `asis_output()` has the same effect as `results = 'asis'`, but saves us
84 the effort to provide this chunk option explicitly. Now we check how the
85 printing behavior is changed. We print a number, a character vector, a list, a
86 data frame, and write a character value using `cat()` in the chunk below:
87
88 ```{r knit-print}
89 1 + 1
90 head(letters)
91 list(a = 1, b = 9:4)
92 head(mtcars)
93 cat('This is cool.')
94 ```
95
96 We see all objects except the data frame were printed "normally"[^2]. The data
97 frame was printed as a real table. Note you do not have to use `kable()` to
98 create tables -- there are many other options such as **xtable**. Just make sure
99 the print method returns a character string.
100
101 [^2]: The two hashes `##` were from the chunk option `comment`; you can turn
102 them off by `comment = ''`.
103
104 The [**printr**](https://github.com/yihui/printr) package is a companion to
105 **knitr** containing printing methods for some common objects like matrices and
106 data frames. Users only need to load this package to get attractive printed
107 results. A major factor to consider (which has been considered in **printr**)
108 when defining a printing method is the output format. For example, the table
109 syntax can be entirely different when the output is LaTeX vs when it is
110 Markdown.
111
112 It is strongly recommended that your S3 method has a `...` argument, so that
113 your method can safely ignore arguments that are passed to `knit_print()` but
114 not defined in your method. At the moment, a `knit_print()` method can have two
115 optional arguments:
116
117 - the `options` argument takes a list of the current chunk options;
118 - the `inline` argument indicates if the method is called in code chunks or
119 inline R code;
120
121 Depending on your application, you may optionally use these arguments. Here are
122 some examples:
123
124 ```{r eval=FALSE, tidy=FALSE}
125 knit_print.classA = function(x, ...) {
126 # ignore options and inline
127 }
128 knit_print.classB = function(x, options, ...) {
129 # use the chunk option out.height
130 asis_output(paste0(
131 '<iframe src="https://yihui.org" height="', options$out.height, '"></iframe>',
132 ))
133 }
134 knit_print.classC = function(x, inline = FALSE, ...) {
135 # different output according to inline=TRUE/FALSE
136 if (inline) {
137 'inline output for classC'
138 } else {
139 'chunk output for classC'
140 }
141 }
142 knit_print.classD = function(x, options, inline = FALSE, ...) {
143 # use both options and inline
144 }
145 ```
146
147 Note that when *using* your (or another) `knit_print()` method *inline* (if it
148 supports that), you must not call `knit_print()` on the object, but just have it
149 return. For example, your inline code should read `` `r c("foo")` `` and *not*
150 `` `r knit_print(c("foo"))` ``. The latter inline code would yield the methods'
151 result for *in-chunk* (not inline), because, as set up in the above,
152 `knit_print()` methods default to `inline = FALSE`. This default gets
153 overwritten depending on the context in which `knit_print()` is called (inline
154 or in-chunk), only when `knit_print()` is called by **knitr** (not you) via the
155 `render` option (see below). You can, of course, always manually set the inline
156 option `` `r knit_print(c("foo"), inline = TRUE)` ``, but that's a lot of
157 typing.
158
159 ## A Low-level Explanation
160
161 You can skip this section if you do not care about the low-level implementation
162 details.
163
164 ### The `render` option
165
166 As mentioned before, the chunk option `render` is a function that defaults to
167 `knit_print()`. We can certainly use other render functions. For example, we
168 create a dummy function that always says "I do not know what to print" no matter
169 what objects it receives:
170
171 ```{r}
172 dummy_print = function(x, ...) {
173 cat("I do not know what to print!")
174 # this function implicitly returns an invisible NULL
175 }
176 ```
177
178 Now we use the chunk option `render = dummy_print`:
179
180 ```{r knit-print, render=dummy_print, collapse=TRUE}
181 ```
182
183 Note the `render` function is only applied to visible objects. There are cases
184 in which the objects returned are invisible, e.g. those wrapped in
185 `invisible()`.
186
187 ```{r}
188 1 + 1
189 invisible(1 + 1)
190 invisible(head(mtcars))
191 x = 1:10 # invisibly returns 1:10
192 ```
193
194 ### Metadata
195
196 The print function can have a side effect of passing "metadata" about objects to
197 **knitr**, and **knitr** will collect this information as it prints objects. The
198 motivation of collecting metadata is to store external dependencies of the
199 objects to be printed. Normally we print an object only to obtain a text
200 representation, but there are cases that can be more complicated. For example, a
201 [**ggvis**](https://ggvis.rstudio.com/) graph requires external JavaScript and
202 CSS dependencies such as `ggvis.js`. The graph itself is basically a fragment of
203 JavaScript code, which will not work unless the required libraries are loaded
204 (in the HTML header). Therefore we need to collect the dependencies of an object
205 beside printing the object itself.
206
207 One way to specify the dependencies is through the `meta` argument of
208 `asis_output()`. Here is a pseudo example:
209
210 ```{r eval=FALSE, tidy=FALSE}
211 # pseudo code
212 knit_print.ggvis = function(x, ...) {
213 res = ggvis::print_this_object(x)
214 knitr::asis_output(res, meta = list(
215 ggvis = list(
216 version = '0.1.0',
217 js = system.file('www', 'js', 'ggvis.js', package = 'ggvis'),
218 css = system.file('www', 'www', 'ggvis.css', package = 'ggvis')
219 )
220 ))
221 }
222 ```
223
224 Then when **knitr** prints a **ggvis** object, the `meta` information will be
225 collected and stored. After knitting is done, we can obtain a list of all the
226 dependencies via `knit_meta()`. It is very likely that there are duplicate
227 entries in the list, and it is up to the package authors to clean them up, and
228 process the metadata list in their own way (e.g. write the dependencies into the
229 HTML header). We give a few more quick and dirty examples below to see how
230 `knit_meta()` works.
231
232 Now we define a print method for `foo` objects:
233
234 ```{r tidy=FALSE}
235 library(knitr)
236 knit_print.foo = function(x, ...) {
237 res = paste('> **This is a `foo` object**:', x)
238 asis_output(res, meta = list(
239 js = system.file('www', 'shared', 'shiny.js', package = 'shiny'),
240 css = system.file('www', 'shared', 'shiny.css', package = 'shiny')
241 ))
242 }
243 ```
244
245 See what happens when we print `foo` objects:
246
247 ```{r}
248 new_foo = function(x) structure(x, class = 'foo')
249 new_foo('hello')
250 ```
251
252 Check the metadata now:
253
254 ```{r}
255 str(knit_meta(clean = FALSE))
256 ```
257
258 Another `foo` object:
259
260 ```{r}
261 new_foo('world')
262 ```
263
264 Similarly for `bar` objects:
265
266 ```{r}
267 knit_print.bar = function(x, ...) {
268 asis_output(x, meta = list(head = '<script>console.log("bar!")</script>'))
269 }
270 new_bar = function(x) structure(x, class = 'bar')
271 new_bar('> **hello** world!')
272 new_bar('> hello **world**!')
273 ```
274
275 The final version of the metadata, and clean it up:
276
277 ```{r}
278 str(knit_meta())
279 str(knit_meta()) # empty now, because clean = TRUE by default
280 ```
281
282 ### For package authors
283
284 If you are implementing a custom print method in your own package, here are two
285 tips:
286
287 1. With R \>= 3.6.0 (2019-04-26), you can declare the S3 method in the package
288 `NAMESPACE` with `S3method(knitr::knit_print, class)`. If you use
289 **roxygen2** package, that means a roxygen comment like this:
290
291 ``` r
292 #' @exportS3Method knitr::knit_print
293 knit_print.class <-
294 ```
295
296 With this method, you do not need to import **knitr** to your package, i.e.,
297 **knitr** can be listed in `Suggests` and not necessarily `Imports` in the
298 package `DESCRIPTION`. The S3 methods will be automatically registered when
299 **knitr** is actually loaded.
300
301 For R \< 3.6.0, you need to import `knit_print` in your package namespace
302 via `importFrom(knitr, knit_print)` (or roxygen:
303 `#' @importFrom knitr knit_print`) (see [the **printr**
304 package](https://github.com/yihui/printr) for an example).
305
306 2. `asis_output()` is simply a function that marks an object with the class
307 `knit_asis`, and you do not have to import this function to your package,
308 either---just let your print method return
309 `structure(x, class = 'knit_asis')`, and if there are additional metadata,
310 just put it in the `knit_meta` attribute; here is the source code of this
311 function:
312
313 ```{r}
314 knitr::asis_output
315 ```
316
317 You may put **knitr** in the `Suggests` field in `DESCRIPTION`, and use
318 `knitr::asis_output()`, so that you can avoid the "hard" dependency on
319 **knitr**.
320
321 ```{r clean-up, include=FALSE}
322 # R compiles all vignettes in the same session, which can be bad
323 rm(list = ls(all = TRUE))
324 ```