| 1 |
# [pander: An R Pandoc Writer](https://github.com/Rapporter/pander) |
| 2 |
|
| 3 |
The main aim of the *pander* [R](https://r-project.org) package is to provide a minimal and easy tool for rendering **R objects** into [Pandoc](https://johnmacfarlane.net/pandoc/)'s **markdown**. The package is also capable of exporting/converting complex Pandoc documents (reports) in [various ways](#creating-pandoc-documents). Regarding the difference between `pander` and other packages for exporting R objects to different file formats, please refer to this [section](#difference-from-other-rendering-packages). |
| 4 |
|
| 5 |
Current build and test coverage status: [](https://app.codecov.io/github/Rapporter/pander?branch=master). |
| 6 |
|
| 7 |
Some CRAN statistics: [](https://cran.r-project.org/package=pander) [](https://cran.r-project.org/package=pander) |
| 8 |
|
| 9 |
# Installation |
| 10 |
|
| 11 |
The stable version [](https://cran.r-project.org/package=pander) can be installed easily in the `R` console like any other package: |
| 12 |
|
| 13 |
```r |
| 14 |
install.packages('pander') |
| 15 |
``` |
| 16 |
|
| 17 |
On the other hand, I welcome everyone to use the most recent version of the package with quick-fixes, new features and probably new bugs. It's currently hosted on [GitHub](https://github.com/Rapporter/pander). To get the latest development version from [GitHub](https://github.com/Rapporter/pander) of the `devtools` package from [CRAN](https://cran.r-project.org/package=devtools): |
| 18 |
|
| 19 |
```r |
| 20 |
devtools::install_github('Rapporter/pander') |
| 21 |
``` |
| 22 |
|
| 23 |
## Dependencies |
| 24 |
|
| 25 |
Few cool packages from CRAN are needed for installing and/or using `pander`: |
| 26 |
|
| 27 |
* [digest](https://cran.r-project.org/package=digest) to compute hashes while caching, |
| 28 |
* [Rcpp](https://cran.r-project.org/package=Rcpp) to compile certain functions used by the package. |
| 29 |
|
| 30 |
And there are also a few optional suggested or supported R packages, such as: |
| 31 |
|
| 32 |
* [sylly](https://cran.r-project.org/package=sylly) to use hyphenation when splitting large table cells, |
| 33 |
* [lattice](https://cran.r-project.org/package=lattice) and [ggplot2](https://cran.r-project.org/package=ggplot2) for unified plot theme, |
| 34 |
* [logger](https://cran.r-project.org/package=logger) for logging capabilities inside `evals`, |
| 35 |
* [survival](https://cran.r-project.org/package=survival), [microbenchmark](https://cran.r-project.org/package=microbenchmark), [zoo](https://cran.r-project.org/package=zoo), [nlme](https://cran.r-project.org/package=nlme), [descr](https://cran.r-project.org/package=descr), [MASS](https://cran.r-project.org/package=MASS), [tables](https://cran.r-project.org/package=tables), [reshape](https://cran.r-project.org/package=reshape), [memisc](https://cran.r-project.org/package=memisc), [Epi](https://cran.r-project.org/package=Epi), [randomForest](https://cran.r-project.org/package=randomForest), [tseries](https://cran.r-project.org/package=tseries), [rms](https://cran.r-project.org/package=rms) packages include some supported R classes, |
| 36 |
* and *pander* can be also very useful inside of [knitr](https://cran.r-project.org/package=knitr). More information about how to use *pander* and *knitr* can be found specialized vignette, which can be accessed by `vignette('knitr', package = 'pander')` or available online [here](https://rapporter.github.io/pander/knitr.html). |
| 37 |
|
| 38 |
### Pandoc |
| 39 |
|
| 40 |
*pander* heavily builds on [Pandoc](https://johnmacfarlane.net/pandoc), which should be **pre-installed** before trying to convert your reports to [different formats](https://johnmacfarlane.net/pandoc/). Although **main functions work without Pandoc**, e.g. you can transform R objects into markdown or generate a markdown formatted report via [Pandoc.brew](#brew-to-pandoc) or the custom [reference class](#live-report-generation), but installing that great piece of software is suggested if you want to convert markdown to PDF/docx/HTML or other formats. |
| 41 |
|
| 42 |
Starting v0.98.932 [RStudio](https://posit.co/) comes with a bundled `Pandoc` binary, so one can save the tedious steps of installing Pandoc. |
| 43 |
|
| 44 |
If you do not have RStudio installed, please refer to the [installation process of Pandoc](https://johnmacfarlane.net/pandoc/installing.html), which is quite straightforward on most-popular operating systems: download and run the binary (a few megabytes), and get a full-blown document converter in a few seconds/minutes. On some Linux distributions, it might be a bit more complicated (as repositories tend to provide out-dated versions of Pandoc, so you would need `cabal-install` to [install from sources](https://johnmacfarlane.net/pandoc/installing.html#all-platforms)). Please do not forget to restart your R session to update your `PATH` after installation! |
| 45 |
|
| 46 |
# Helper functions |
| 47 |
|
| 48 |
The package contains numerous helper functions, which render user specified inputs in Pandoc's markdown format or apply some extra formatting on it. All Pandoc-related functions' names are starting with `pandoc`. For example `pandoc.table` is used for rendering tables in markdown. For a technical documentation, see the HTML help files of the package at [Rdocumentation](https://www.rdocumentation.org/packages/pander). |
| 49 |
|
| 50 |
<a id="primitive-functions"></a> |
| 51 |
|
| 52 |
All `pandoc` functions generally prints to console and do not return anything by default. If you want the opposite, to get markdown in a string, call each function ending in `.return`, for example `pandoc.table.return`. For more details, please see the official documentation in e.g. `?pandoc.strong`. |
| 53 |
|
| 54 |
The full list of currently available primitive Pandoc-related functions are: |
| 55 |
|
| 56 |
* pandoc.indent |
| 57 |
* pandoc.p |
| 58 |
* pandoc.strong |
| 59 |
* pandoc.emphasis |
| 60 |
* pandoc.strikeout |
| 61 |
* pandoc.verbatim |
| 62 |
* pandoc.link |
| 63 |
* pandoc.image |
| 64 |
* pandoc.date |
| 65 |
* pandoc.formula |
| 66 |
* pandoc.footnote |
| 67 |
* pandoc.horizontal.rule |
| 68 |
* pandoc.header |
| 69 |
* pandoc.title |
| 70 |
|
| 71 |
<a id="lists"></a> |
| 72 |
For example there is a helper function rendering R **lists** into markdown: |
| 73 |
|
| 74 |
```r |
| 75 |
> l <- list( |
| 76 |
+ "First list element", |
| 77 |
+ paste0(1:5, '. subelement'), |
| 78 |
+ "Second element", |
| 79 |
+ list('F', 'B', 'I', c('phone', 'pad', 'talics'))) |
| 80 |
> pandoc.list(l, 'roman') |
| 81 |
``` |
| 82 |
Which command produces the following output: |
| 83 |
```<%= |
| 84 |
l <- list("First list element", paste0(1:5, '. subelement'), "Second element", list('F', 'B', 'I', c('phone', 'pad', 'talics'))) |
| 85 |
pandoc.list.return(l, 'roman') |
| 86 |
%> |
| 87 |
``` |
| 88 |
|
| 89 |
<a id="tables"></a> |
| 90 |
|
| 91 |
# Markdown tables |
| 92 |
|
| 93 |
One of the most popular feature in *pander* is `pandoc.table`, rendering most tabular R objects into markdown tables with various options and settings (e.g. [style](#style), [caption](#caption), [cell highlighting](#highlight-cells), [cell alignment](#cell-alignment), [width](#table-and-cell-width)). This section aims to provide quick introduction to most common options, but for more usage/implementation details and examples, please refer to specialized vignette, which can be accessed by `vignette('pandoc_table')` or available online [here](https://rapporter.github.io/pander/pandoc_table.html). |
| 94 |
|
| 95 |
Let's start with a small example: |
| 96 |
|
| 97 |
```r |
| 98 |
> pandoc.table(mtcars[1:3, 1:4]) |
| 99 |
``` |
| 100 |
Which command produces the following output by default: |
| 101 |
```<%=mtcars[1:3, 1:4]%> |
| 102 |
``` |
| 103 |
|
| 104 |
<a id="style"></a><a id="styles"></a> |
| 105 |
|
| 106 |
Please note that all below features are also supported by the more concise `pander` [generic S3 method](#generic-pander-method)! |
| 107 |
|
| 108 |
## Formats |
| 109 |
|
| 110 |
All [four Pandoc formats](https://johnmacfarlane.net/pandoc/README.html#tables) are supported by *pander*. From those (*multiline*, *simple*, *grid*, *pipe/rmarkdown*), I'd suggest sticking to the default `multiline` format with the most features, except when using `rmarkdown` v1.0 or jupyter notebook, where `multiline` is not supported (for this end the default table format is `rmarkdown` when `pander` is called inside of a jupyter notebook). Please see a few examples below: |
| 111 |
|
| 112 |
<a id="multiline-table"></a> |
| 113 |
|
| 114 |
The default style is the [`multiline` format](https://johnmacfarlane.net/pandoc/README.html#multiline-tables) (except for calling `pander` inside of a of a jupyter notebook) as most features (e.g. multi-line cells and alignment) are supported: |
| 115 |
|
| 116 |
```rout |
| 117 |
> m <- mtcars[1:2, 1:3] |
| 118 |
> pandoc.table(m) |
| 119 |
<%= |
| 120 |
pandoc.table.return(mtcars[1:2, 1:3]) |
| 121 |
%> |
| 122 |
``` |
| 123 |
|
| 124 |
While [`simple` tables](https://johnmacfarlane.net/pandoc/README.html#simple-tables) are much more compact, but do not support line breaks in cells: |
| 125 |
|
| 126 |
```rout |
| 127 |
> pandoc.table(m, style = "simple") |
| 128 |
<%= |
| 129 |
pandoc.table.return(mtcars[1:2, 1:3], style = "simple") |
| 130 |
%> |
| 131 |
``` |
| 132 |
|
| 133 |
My personal favorite, the [`grid` format](https://johnmacfarlane.net/pandoc/README.html#grid-tables) is really handy for [emacs](https://www.emacswiki.org/emacs/TableMode) users and it does support line breaks inside of cells, but cell alignment is not possible in most parsers: |
| 134 |
|
| 135 |
```rout |
| 136 |
> pandoc.table(m, style = "grid") |
| 137 |
<%= |
| 138 |
pandoc.table.return(mtcars[1:2, 1:3], style = "grid") |
| 139 |
%> |
| 140 |
``` |
| 141 |
|
| 142 |
And the so called `rmarkdown` or [pipe table format](https://johnmacfarlane.net/pandoc/README.html#pipe-tables) is often used directly with `knitr`, since it was supporters by the first versions of the `markdown` package: |
| 143 |
|
| 144 |
```rout |
| 145 |
> pandoc.table(m, style = "rmarkdown") |
| 146 |
<%= |
| 147 |
pandoc.table.return(mtcars[1:2, 1:3], style = "rmarkdown") |
| 148 |
%> |
| 149 |
``` |
| 150 |
|
| 151 |
But once again, you should simply stick to the default [multiline table format](#multiline-table) in most cases. Otherwise, it's wise to update the default table format via [`panderOptions`](#pander-options). |
| 152 |
|
| 153 |
## Caption |
| 154 |
|
| 155 |
It's really easy to add a **caption** to a table: |
| 156 |
|
| 157 |
```rout |
| 158 |
> pandoc.table(m, style = "grid", caption = "Hello caption!") |
| 159 |
<%= |
| 160 |
pandoc.table.return(mtcars[1:2, 1:3], style = "grid", caption = 'Hello caption!') |
| 161 |
%> |
| 162 |
``` |
| 163 |
|
| 164 |
For more convenient and flexible usage, you might be interested in the special `set.caption` helper function. Call the function at any time, and the next table or plot will catch up the provided caption: |
| 165 |
|
| 166 |
```rout |
| 167 |
> set.caption("Hello caption!") |
| 168 |
> pandoc.table(m) |
| 169 |
<%= |
| 170 |
set.caption("Hello caption!") |
| 171 |
pandoc.table.return(mtcars[1:2, 1:3]) |
| 172 |
%> |
| 173 |
``` |
| 174 |
|
| 175 |
Unless `permanent` option is set for `TRUE` (by default), caption will be set only for next table. To disable permanently set caption, just call `set.caption(NULL)` or call `set.caption` with `permanent` parameter being set to `FALSE`. |
| 176 |
|
| 177 |
<a id="highlight-cells"></a> |
| 178 |
|
| 179 |
## Highlighting cells |
| 180 |
|
| 181 |
One of the fanciest features in *pander* is the ease of highlighting rows, columns or any cells in a table. This is a real markdown feature without custom HTML or LaTeX-only tweaks, so all HTML/PDF/MS Word/OpenOffice etc. formats are supported. |
| 182 |
|
| 183 |
This can be achieved by calling `pandoc.table` directly and passing any (or more) of the following arguments **or** calling the R function with the same names before rendering a table with either the `pander` [generic S3 method](#generic-pander-method) or via `pandoc.table`: |
| 184 |
|
| 185 |
* emphasize.italics.rows |
| 186 |
* emphasize.italics.cols |
| 187 |
* emphasize.italics.cells |
| 188 |
* emphasize.strong.rows |
| 189 |
* emphasize.strong.cols |
| 190 |
* emphasize.strong.cells |
| 191 |
* emphasize.verbatim.rows |
| 192 |
* emphasize.verbatim.cols |
| 193 |
* emphasize.verbatim.cells |
| 194 |
|
| 195 |
The `emphasize.italics` helpers would turn the affected cells to *italic*, `emphasize.strong` would apply a **bold** style to the cell and `emphasize.verbatim` would apply a `verbatim` style to the cell. A cell can be also *italic*, **bold** and `verbatim` at the same time. |
| 196 |
|
| 197 |
Those functions and arguments ending in `rows` or `cols` take a vector (like which columns or rows to emphasize in a table), while the `cells` argument take either a vector (for one dimensional "tables") or an array-like data structure with two columns holding row and column indexes of cells to be emphasized -- just like what `which(..., arr.ind = TRUE)` returns. A quick-example: |
| 198 |
|
| 199 |
```rout |
| 200 |
> t <- mtcars[1:3, 1:5] |
| 201 |
> emphasize.italics.cols(1) |
| 202 |
> emphasize.italics.rows(1) |
| 203 |
> emphasize.strong.cells(which(t > 20, arr.ind = TRUE)) |
| 204 |
> pandoc.table(t) |
| 205 |
<%= |
| 206 |
t <- mtcars[1:3, 1:5] |
| 207 |
emphasize.italics.cols(1) |
| 208 |
emphasize.italics.rows(1) |
| 209 |
emphasize.strong.cells(which(t > 20, arr.ind = TRUE)) |
| 210 |
pandoc.table.return(t) |
| 211 |
pandoc.table(t, emphasize.verbatim.rows = 1, emphasize.strong.cells = which(t > 20, arr.ind = TRUE)) |
| 212 |
%> |
| 213 |
``` |
| 214 |
|
| 215 |
For more examples, please see our "[Highlight cells in markdown tables](http://blog.rapporter.net/2013/04/hihglight-cells-in-markdown-tables.html)" blog post. |
| 216 |
|
| 217 |
## Cell alignment |
| 218 |
|
| 219 |
You can specify the alignment of the cells (left, right or center/centre) in a table directly by setting the `justify` parameter: |
| 220 |
|
| 221 |
```rout |
| 222 |
> pandoc.table(head(iris[,1:3], 2), justify = c('right', 'center', 'left')) |
| 223 |
<%= |
| 224 |
pandoc.table.return(head(iris[,1:3], 2), justify = c('right', 'center', 'left')) |
| 225 |
%> |
| 226 |
``` |
| 227 |
|
| 228 |
Or pre-define the alignment for (all future) `pandoc.table` or the `pander` [S3 generic method](#generic-pander-method) by a helper function: |
| 229 |
|
| 230 |
```rout |
| 231 |
> set.alignment('left', row.names = 'right') |
| 232 |
> pandoc.table(mtcars[1:2, 1:5]) |
| 233 |
<%= |
| 234 |
set.alignment('left', row.names = 'right') |
| 235 |
pandoc.table.return(mtcars[1:2, 1:5]) |
| 236 |
%> |
| 237 |
``` |
| 238 |
|
| 239 |
Just like with [captions](#caption), you can also specify the `permanent` option to be `TRUE` to update the default cell alignment for all future tables. And beside using `set.alignment` helper function or passing parameters directly to `pandoc.table`, you may also set the default alignment styles with [`panderOptions`](#pander-options). |
| 240 |
|
| 241 |
What's even more fun, you can specify a function that takes the R object as its argument to compute some unique alignment for your table based on e.g. column values or variable types: |
| 242 |
|
| 243 |
```rout |
| 244 |
> panderOptions('table.alignment.default', |
| 245 |
+ function(df) |
| 246 |
+ ifelse(sapply(df, mean) > 2, 'left', 'right')) |
| 247 |
> pandoc.table(head(iris[,1:3], 2)) |
| 248 |
<%= |
| 249 |
potad <- panderOptions('table.alignment.default') |
| 250 |
panderOptions('table.alignment.default', function(df) ifelse(sapply(df, mean) > 2, 'left', 'right')) |
| 251 |
pandoc.table.return(head(iris[,1:3], 2)) |
| 252 |
panderOptions('table.alignment.default', potad) |
| 253 |
%> |
| 254 |
``` |
| 255 |
|
| 256 |
## Table and cell width |
| 257 |
|
| 258 |
`pandoc.table` can also deal with the problem of really **wide tables**. Ever had an issue in LaTeX or MS Word when tried to print a correlation matrix of 40 variables? Not a problem any more as you can split up the table with auto-added captions. The `split.table` option defaults to 80 characters: |
| 259 |
|
| 260 |
```rout |
| 261 |
> pandoc.table(mtcars[1:2, ], style = "grid", caption = "Hello caption!") |
| 262 |
<%= |
| 263 |
gsub('\n\n \n\n', '\n\n', pandoc.table.return(mtcars[1:2, ], style = "grid", caption = 'Hello caption!')) |
| 264 |
%> |
| 265 |
``` |
| 266 |
|
| 267 |
And too wide cells can also be split by line breaks. The maximum number of characters in a cell is specified by `split.cells` parameter (default to 30), can be a single value, vector (values for each column separately) and relative vector (percentages of `split.tables` parameter): |
| 268 |
|
| 269 |
```rout |
| 270 |
> df <- data.frame(a = 'Lorem ipsum', b = 'dolor sit', c = 'amet') |
| 271 |
> pandoc.table(df, split.cells = 5) |
| 272 |
<%= |
| 273 |
df <- data.frame(a = 'Lorem ipsum', b = 'dolor sit', c = 'amet') |
| 274 |
pandoc.table.return(df, split.cells = 5) |
| 275 |
%> |
| 276 |
> pandoc.table(df, split.cells = c(5, 20, 5)) |
| 277 |
<%= |
| 278 |
pandoc.table.return(df, split.cells = c(5, 20, 5)) |
| 279 |
%> |
| 280 |
> pandoc.table(df, split.cells = c("80%", "10%", "10%")) |
| 281 |
<%= |
| 282 |
pandoc.table.return(df, split.cells = c("80%", "10%", "10%")) |
| 283 |
%> |
| 284 |
``` |
| 285 |
|
| 286 |
If the `sylly` package is installed, `pandoc.table` can even split the cells with hyphening support: |
| 287 |
|
| 288 |
```rout |
| 289 |
> pandoc.table(data.frame(baz = 'foobar'), use.hyphening = TRUE, split.cells = 3) |
| 290 |
<%= |
| 291 |
pandoc.table.return(data.frame(baz = 'foobar'), use.hyphening = TRUE, split.cells = 3) |
| 292 |
%> |
| 293 |
``` |
| 294 |
|
| 295 |
## Minor features |
| 296 |
|
| 297 |
Funtionality described in other sections is most notable, but `pander/pandoc.table` also has smaller nifty features that are worth mentioning: |
| 298 |
|
| 299 |
* `plain.ascii` - allows to have the output without `markdown` markup: |
| 300 |
|
| 301 |
```rout |
| 302 |
> pandoc.table(mtcars[1:3, 1:4]) |
| 303 |
<%= |
| 304 |
pandoc.table.return(mtcars[1:3, 1:4]) |
| 305 |
%> |
| 306 |
> pandoc.table(mtcars[1:3, 1:4], plain.ascii = TRUE) |
| 307 |
<%= |
| 308 |
pandoc.table.return(mtcars[1:3, 1:4], plain.ascii = TRUE) |
| 309 |
%> |
| 310 |
``` |
| 311 |
|
| 312 |
* `missing` - set a string to replace missing values: |
| 313 |
|
| 314 |
```rout |
| 315 |
> m <- mtcars[1:3, 1:5] |
| 316 |
> m$mpg <- NA |
| 317 |
> pandoc.table(m, missing = '?') |
| 318 |
<%= |
| 319 |
m <- mtcars[1:3, 1:5] |
| 320 |
m$mpg <- NA |
| 321 |
pandoc.table.return(m, missing = '?') |
| 322 |
%> |
| 323 |
``` |
| 324 |
|
| 325 |
* `keep.line.breaks` - allows to preserve line breaks inside cells. Not that by default `pandoc.table` automatically omits all line breaks found in each table cell to be able to apply the `table.split` functionality. |
| 326 |
|
| 327 |
```rout |
| 328 |
> m <- data.frame(a="foo\nbar", b="pander") |
| 329 |
> pandoc.table(m) |
| 330 |
<%= |
| 331 |
m <- data.frame(a="foo\nbar", b="pander") |
| 332 |
pandoc.table.return(m) |
| 333 |
%> |
| 334 |
> pandoc.table(m, keep.line.breaks = TRUE) |
| 335 |
<%= |
| 336 |
pandoc.table.return(m, keep.line.breaks = TRUE) |
| 337 |
%> |
| 338 |
``` |
| 339 |
|
| 340 |
To see all possible options, please check [`?pandoc.table`](https://www.rdocumentation.org/packages/pander/functions/pandoc.table.return) |
| 341 |
|
| 342 |
And please note, that all above mentioned features are also supported by the `pander` [generic S3 method](#generic-pander-method) and defaults can be updated via [`panderOptions`](#pander-options) for permanent settings. |
| 343 |
|
| 344 |
# Generic pander method |
| 345 |
|
| 346 |
`pander` or `pandoc` (call as you wish) can deal with a bunch of R object types as being a pandocized `S3` generic method with a variety of already supported classes: |
| 347 |
|
| 348 |
<a id="supported-r-classes"></a> |
| 349 |
|
| 350 |
```rout |
| 351 |
> methods(pander) |
| 352 |
[1] pander.anova* pander.aov* pander.aovlist* pander.Arima* pander.call* |
| 353 |
[6] pander.cast_df* pander.character* pander.clogit* pander.coxph* pander.cph* |
| 354 |
[11] pander.CrossTable* pander.data.frame* pander.Date* pander.default* pander.density* |
| 355 |
[16] pander.describe* pander.evals* pander.factor* pander.formula* pander.ftable* |
| 356 |
[21] pander.function* pander.glm* pander.Glm* pander.gtable* pander.htest* |
| 357 |
[26] pander.image* pander.irts* pander.list* pander.lm* pander.lme* |
| 358 |
[31] pander.logical* pander.lrm* pander.manova* pander.matrix* pander.microbenchmark* |
| 359 |
[36] pander.mtable* pander.name* pander.nls* pander.NULL* pander.numeric* |
| 360 |
[41] pander.ols* pander.orm* pander.polr* pander.POSIXct* pander.POSIXlt* |
| 361 |
[46] pander.prcomp* pander.randomForest* pander.rapport* pander.rlm* pander.sessionInfo* |
| 362 |
[51] pander.smooth.spline* pander.stat.table* pander.summary.aov* pander.summary.aovlist* pander.summary.glm* |
| 363 |
[56] pander.summary.lm* pander.summary.lme* pander.summary.manova* pander.summary.nls* pander.summary.polr* |
| 364 |
[61] pander.summary.prcomp* pander.summary.rms* pander.summary.survreg* pander.summary.table* pander.survdiff* |
| 365 |
[66] pander.survfit* pander.survreg* pander.table* pander.tabular* pander.ts* |
| 366 |
[71] pander.zoo* |
| 367 |
``` |
| 368 |
|
| 369 |
If you think that pander lacks support for any other R class(es), please feel free to open a [ticket](https://github.com/Rapporter/pander/pulls) suggesting a new feature or submit [pull request](https://github.com/Rapporter/pander/issues) and we will be happy to extend the package. |
| 370 |
|
| 371 |
Besides the most basic R object types (vectors, matrices, tables or data frames), list-support might be interesting for you: |
| 372 |
|
| 373 |
```rout |
| 374 |
> pander(list(a = 1, b = 2, c = table(mtcars$am), x = list(myname = 1, 2), 56)) |
| 375 |
<%=pander(list(a = 1, b = 2, c = table(mtcars$am), x = list(myname = 1, 2), 56))%> |
| 376 |
``` |
| 377 |
|
| 378 |
A nested list can be seen above with a table and all (optional) list names. As a matter of fact, `pander.list` is the default method of `pander` too, when you call it on an unsupported R object class: |
| 379 |
|
| 380 |
```rout |
| 381 |
> x <- chisq.test(table(mtcars$am, mtcars$gear)) |
| 382 |
> class(x) <- "I've never heard of!" |
| 383 |
> pander(x) |
| 384 |
<%= |
| 385 |
x <- chisq.test(table(mtcars$am, mtcars$gear)) |
| 386 |
class(x) <- 'I\'ve never heard of!' |
| 387 |
x |
| 388 |
%> |
| 389 |
``` |
| 390 |
|
| 391 |
So `pander` showed a not known class in an (almost) user-friendly way. And we got some warnings too styled with [Pandoc **footnote**](https://johnmacfarlane.net/pandoc/README.html#footnotes)! If that document is exported to e.g. `HTML` or `pdf`, then the error/warning message could be found on the bottom of the page with a link. *Note*: there were two warnings in the above call - both captured and returned! Well, this is the feature of `Pandoc.brew`, see [below](#brew-to-pandoc). |
| 392 |
|
| 393 |
But the output of different **statistical methods** are tried to be prettyfied. Some the above call normally returns like: |
| 394 |
|
| 395 |
```rout |
| 396 |
> pander(chisq.test(table(mtcars$am, mtcars$gear))) |
| 397 |
<%= chisq.test(table(mtcars$am, mtcars$gear)) %> |
| 398 |
``` |
| 399 |
|
| 400 |
A few other examples on the supported R classes: |
| 401 |
|
| 402 |
```rout |
| 403 |
> pander(t.test(extra ~ group, data = sleep)) |
| 404 |
<%=t.test(extra ~ group, data = sleep)%> |
| 405 |
|
| 406 |
> ## Dobson (1990) Page 93: Randomized Controlled Trial (examples from: ?glm) |
| 407 |
> counts <- c(18, 17, 15, 20, 10, 20, 25, 13, 12) |
| 408 |
> outcome <- gl(3, 1, 9) |
| 409 |
> treatment <- gl(3, 3) |
| 410 |
> m <- glm(counts ~ outcome + treatment, family = poisson()) |
| 411 |
> pander(m) |
| 412 |
<%= |
| 413 |
counts <- c(18, 17, 15, 20, 10, 20, 25, 13, 12) |
| 414 |
outcome <- gl(3, 1, 9) |
| 415 |
treatment <- gl(3, 3) |
| 416 |
m <- glm(counts ~ outcome + treatment, family = poisson()) |
| 417 |
m |
| 418 |
%> |
| 419 |
|
| 420 |
> pander(anova(m)) |
| 421 |
<%=anova(m)%> |
| 422 |
|
| 423 |
> pander(aov(m)) |
| 424 |
<%=aov(m)%> |
| 425 |
|
| 426 |
> pander(prcomp(USArrests)) |
| 427 |
<%=prcomp(USArrests)%> |
| 428 |
|
| 429 |
> pander(density(mtcars$hp)) |
| 430 |
<%=density(mtcars$hp)%> |
| 431 |
|
| 432 |
> ## Don't like scientific notation? |
| 433 |
> panderOptions('round', 2) |
| 434 |
> pander(density(mtcars$hp)) |
| 435 |
<% |
| 436 |
panderOptions('round', 2) |
| 437 |
pander(density(mtcars$hp)) |
| 438 |
panderOptions('round', Inf) |
| 439 |
%> |
| 440 |
``` |
| 441 |
|
| 442 |
And of course tables are formatted (e.g. auto add of line breaks, splitting up tables, hyphenation support or markdown format) based on the user specified [`panderOptions`](#pander-options). |
| 443 |
|
| 444 |
# Creating Pandoc documents |
| 445 |
|
| 446 |
The package is also capable of creating complex Pandoc documents (reports) from **R objects** in multiple ways: |
| 447 |
|
| 448 |
* create somehow a markdown text file (e.g. with `brew`, `knitr` or any scripts of yours, maybe with `Pandoc.brew` - see just [below](#brew-to-pandoc)) and transform that to other formats (like HTML, odt, PDF, docx etc.) with `Pandoc.convert` - similarly to [`pandoc` function in knitr](https://yihui.org/knitr/demo/pandoc/). Basically this is a wrapper around a [Pandoc](https://johnmacfarlane.net/pandoc/) call, which has not much to do with R actually. |
| 449 |
|
| 450 |
* users might write some reports with literate programming (similar to `knitr`) in a forked version of [brew](https://cran.r-project.org/package=brew) syntax resulting. This means that the user can include R code chunks in a document, and brewing that results in a pretty Pandoc's markdown document and also in a **bunch of other formats** (like HTML, odt, PDF, docx etc.). The great advantage of this [function](#brew-to-pandoc) is that you do not have to transform your R objects to markdown manually, it's all handled automagically. |
| 451 |
|
| 452 |
*Example*: this [`README.md`](https://github.com/Rapporter/pander/blob/master/README.md) is cooked with [`Pandoc.brew`](#brew-to-pandoc) based on [`inst/README.brew`](https://github.com/Rapporter/pander/blob/master/inst/README.brew) and also exported to [HTML](https://rapporter.github.io/pander/). Details can be found [below](#brew-to-pandoc) or head directly to [examples](#examples). |
| 453 |
|
| 454 |
<!-- endlist --> |
| 455 |
|
| 456 |
* and users might create a report in a live R session by adding some R objects and paragraphs to a `Pandoc` reference class object. Details can be found [below](#live-report-generation). |
| 457 |
|
| 458 |
## Brew to Pandoc |
| 459 |
|
| 460 |
The [brew](https://cran.r-project.org/package=brew) package, which is a templating framework for report generation, has not been updated on CRAN since 2011, but it's still used in bunch of R projects based on its simple design and useful features in literate programming. For a quick overview, please see the following documents if you are not familiar with `brew`: |
| 461 |
|
| 462 |
* [slides on "Building a reporting sytem with BREW"](https://www.slideshare.net/xavierguardiola/building-a-reporting-sytem-with-brew) |
| 463 |
* [learnr blogpost on brew](https://learnr.wordpress.com/2009/09/09/brew-creating-repetitive-reports/) |
| 464 |
|
| 465 |
**In short**: a `brew` document is a simple text file with some special tags. `Pandoc.brew` uses only two of them (as building on a personalized version of Jeff's really great `brew` function): |
| 466 |
|
| 467 |
* `<<%= '%' %> ... <%= '%' %>>` stand for running inline R commands as usual, |
| 468 |
* `<<%= '%' %>= ... <%= '%' %>>` does pretty much the same but applies `pander` to the returning R object (instead of `cat` like the original `brew` function does). So putting there any R object, it would return in a nice Pandoc's markdown format with all possible error/warning messages etc. |
| 469 |
|
| 470 |
This latter tries to be smart in some ways: |
| 471 |
|
| 472 |
* A code chunk block (R commands between the tags) can return any number of values at any part of the block. |
| 473 |
* Plots and images are grabbed in the document, rendered to a `png` file and `pander` method would result in a Pandoc markdown formatted image link. This means that the image would be rendered/shown/included in the exported document. |
| 474 |
* All warnings/messages and errors are recorded in the blocks and returned in the document as footnotes or inline messages. |
| 475 |
* All heavy R commands (e.g. those taking more then 0.1 sec to evaluate) are [**cached**](#caching) so re`brew`ing a report would not result in a coffee break. |
| 476 |
|
| 477 |
Besides this, the custom `brew` function can do more and also less compared to the original [`brew` package](https://cran.r-project.org/package=brew). First of all, the internal caching mechanism of `brew` has been removed and rewritten for some extra profits besides improved caching. |
| 478 |
|
| 479 |
For example now multiple R expressions can be passed between the `<<%= '%' %>= ... <%= '%' %>>` tags, and not only the text results, but **the evaluated R objects** are also (invisibly) returned in a structured list. This can be really useful while post-processing the results of `brew`. Quick example: |
| 480 |
|
| 481 |
```rout |
| 482 |
> str(Pandoc.brew(text =' |
| 483 |
+ Pi equals to `<<%= '%' %>= pi <%= '%' %>>`. |
| 484 |
+ And here are some random data: |
| 485 |
+ `<<%= '%' %>= runif(10) <%= '%' %>>` |
| 486 |
+ ')) |
| 487 |
|
| 488 |
Pi equals to _3.142_. |
| 489 |
And here are some random data: |
| 490 |
_0.6631_, _0.849_, _0.06986_, _0.3343_, _0.5209_, _0.3471_, _0.866_, _0.05548_, _0.8933_ and _0.2121_ |
| 491 |
|
| 492 |
List of 2 |
| 493 |
$ :List of 4 |
| 494 |
..$ type : chr "text" |
| 495 |
..$ text :List of 2 |
| 496 |
.. ..$ raw : chr "Pi equals to <%=pi%>.\nAnd here are some random data:\n" |
| 497 |
.. ..$ eval: chr "Pi equals to _3.142_.\nAnd here are some random data:\n" |
| 498 |
..$ chunks:List of 2 |
| 499 |
.. ..$ raw : chr "<%=pi%>" |
| 500 |
.. ..$ eval: chr "_3.142_" |
| 501 |
..$ msg :List of 3 |
| 502 |
.. ..$ messages: NULL |
| 503 |
.. ..$ warnings: NULL |
| 504 |
.. ..$ errors : NULL |
| 505 |
$ :List of 2 |
| 506 |
..$ type : chr "block" |
| 507 |
..$ robject:List of 6 |
| 508 |
.. ..$ src : chr "runif(10)" |
| 509 |
.. ..$ result: num [1:10] 0.6631 0.849 0.0699 0.3343 0.5209 ... |
| 510 |
.. ..$ output: chr "_0.6631_, _0.849_, _0.06986_, _0.3343_, _0.5209_, _0.3471_, _0.866_, _0.05548_, _0.8933_ and _0.2121_" |
| 511 |
.. ..$ type : chr "numeric" |
| 512 |
.. ..$ msg :List of 3 |
| 513 |
.. .. ..$ messages: NULL |
| 514 |
.. .. ..$ warnings: NULL |
| 515 |
.. .. ..$ errors : NULL |
| 516 |
.. ..$ stdout: NULL |
| 517 |
.. ..- attr(*, "class")= chr "evals" |
| 518 |
``` |
| 519 |
|
| 520 |
This document was generated by `Pandoc.brew` based on [`inst/README.brew`](https://github.com/Rapporter/pander/blob/master/inst/README.brew) so the above examples were generated automatically by running: |
| 521 |
|
| 522 |
```r |
| 523 |
Pandoc.brew(system.file('README.brew', package = 'pander')) |
| 524 |
``` |
| 525 |
|
| 526 |
The output is set to `stdout` by default, which means that the resulting text is written to the R console. But setting the `output` to a text file and running Pandoc on that to create a `HTML`, `odt`, `docx` or other document in one go is also possible. To export a brewed file to other then Pandoc's markdown, please use the `convert` parameter. For example: |
| 527 |
|
| 528 |
```r |
| 529 |
text <- paste('# Header', |
| 530 |
'', |
| 531 |
'What a lovely list:\n<<%= '%' %>= as.list(runif(10)) <%= '%' %>>', |
| 532 |
'A wide table:\n<<%= '%' %>= mtcars[1:3, ] <%= '%' %>>', |
| 533 |
'And a nice chart:\n\n<<%= '%' %>= plot(1:10) <%= '%' %>>', |
| 534 |
sep = '\n') |
| 535 |
Pandoc.brew(text = text, output = tempfile(), convert = 'html') |
| 536 |
Pandoc.brew(text = text, output = tempfile(), convert = 'pdf') |
| 537 |
``` |
| 538 |
|
| 539 |
So to brew this README with all R chunks automatically converted to html, please run: |
| 540 |
|
| 541 |
```r |
| 542 |
Pandoc.brew(system.file('README.brew', package='pander'), output = tempfile(), convert = 'html') |
| 543 |
``` |
| 544 |
|
| 545 |
### Examples |
| 546 |
|
| 547 |
The package bundles some examples for `Pandoc.brew` to let you check its features pretty fast. These are: |
| 548 |
|
| 549 |
* [minimal.brew](https://github.com/Rapporter/pander/blob/master/inst/examples/minimal.brew) |
| 550 |
* [short-code-long-report.brew](https://github.com/Rapporter/pander/blob/master/inst/examples/short-code-long-report.brew) |
| 551 |
* [graphs.brew](https://github.com/Rapporter/pander/blob/master/inst/examples/graphs.brew) |
| 552 |
|
| 553 |
To `brew` these examples on your machine, try to run the followings commands: |
| 554 |
|
| 555 |
```r |
| 556 |
Pandoc.brew(system.file('examples/minimal.brew', package='pander')) |
| 557 |
Pandoc.brew(system.file('examples/minimal.brew', package='pander'), output = tempfile(), convert = 'html') |
| 558 |
|
| 559 |
Pandoc.brew(system.file('examples/short-code-long-report.brew', package='pander')) |
| 560 |
Pandoc.brew(system.file('examples/short-code-long-report.brew', package='pander'), output = tempfile(), convert = 'html') |
| 561 |
|
| 562 |
Pandoc.brew(system.file('examples/graphs.brew', package='pander')) |
| 563 |
Pandoc.brew(system.file('examples/graphs.brew', package='pander'), output = tempfile(), convert = 'html') |
| 564 |
``` |
| 565 |
|
| 566 |
For easier access, I have uploaded some exported documents of the above examples as well: |
| 567 |
|
| 568 |
* minimal.brew: [markdown](https://rapporter.github.io/pander/minimal.md) [html](https://rapporter.github.io/pander/minimal.html) [pdf](https://rapporter.github.io/pander/minimal.pdf) [odt](https://rapporter.github.io/pander/minimal.odt) [docx](https://rapporter.github.io/pander/minimal.docx) |
| 569 |
* short-code-long-report.brew: [markdown](https://rapporter.github.io/pander/short-code-long-report.md) [html](https://rapporter.github.io/pander/short-code-long-report.html) [pdf](https://rapporter.github.io/pander/short-code-long-report.pdf) [odt](https://rapporter.github.io/pander/short-code-long-report.odt) [docx](https://rapporter.github.io/pander/short-code-long-report.docx) |
| 570 |
* graphs.brew: [markdown](https://rapporter.github.io/pander/graphs.md) [html](https://rapporter.github.io/pander/graphs.html) [pdf](https://rapporter.github.io/pander/graphs.pdf) [odt](https://rapporter.github.io/pander/graphs.odt) [docx](https://rapporter.github.io/pander/graphs.docx) |
| 571 |
|
| 572 |
Please check out `pdf`, `docx`, `odt` and other formats by changing the above `convert` option on your machine, and do not forget to [give some feedback](https://github.com/Rapporter/pander/issues)! |
| 573 |
|
| 574 |
## Live report generation |
| 575 |
|
| 576 |
`pander` package has a special reference class called `Pandoc` which could collect some blocks in a live R session and export the whole document to Pandoc/PDF/HTML etc. Without any serious further explanations, please check out the below (self-commenting) example: |
| 577 |
|
| 578 |
```r |
| 579 |
## Initialize a new Pandoc object |
| 580 |
myReport <- Pandoc$new() |
| 581 |
|
| 582 |
## Add author, title and date of document |
| 583 |
myReport$author <- 'Gergely Daróczi' |
| 584 |
myReport$title <- 'Demo' |
| 585 |
|
| 586 |
## Or it could be done while initializing |
| 587 |
myReport <- Pandoc$new('Gergely Daróczi', 'Demo') |
| 588 |
|
| 589 |
## Add some free text |
| 590 |
myReport$add.paragraph('Hello there, this is a really short tutorial!') |
| 591 |
|
| 592 |
## Add maybe a header for later stuff |
| 593 |
myReport$add.paragraph('# Showing some raw R objects below') |
| 594 |
|
| 595 |
## Adding a short matrix |
| 596 |
myReport$add(matrix(5,5,5)) |
| 597 |
|
| 598 |
## Or a table with even |
| 599 |
myReport$add.paragraph('Hello table:') |
| 600 |
myReport$add(table(mtcars$am, mtcars$gear)) |
| 601 |
|
| 602 |
## Or a "large" data frame which barely fits on a page |
| 603 |
myReport$add(mtcars) |
| 604 |
|
| 605 |
## And a simple linear model with Anova tables |
| 606 |
ml <- with(lm(mpg ~ hp + wt), data = mtcars) |
| 607 |
myReport$add(ml) |
| 608 |
myReport$add(anova(ml)) |
| 609 |
myReport$add(aov(ml)) |
| 610 |
|
| 611 |
## And do some principal component analysis at last |
| 612 |
myReport$add(prcomp(USArrests)) |
| 613 |
|
| 614 |
## Sorry, I did not show how Pandoc deals with plots: |
| 615 |
myReport$add(plot(1:10)) |
| 616 |
|
| 617 |
## Want to see the report? Just print it: |
| 618 |
myReport |
| 619 |
|
| 620 |
## Exporting to PDF (default) |
| 621 |
myReport$export() |
| 622 |
|
| 623 |
## Or to docx in tempdir(): |
| 624 |
myReport$format <- 'docx' |
| 625 |
myReport$export(tempfile()) |
| 626 |
|
| 627 |
## You do not want to see the generated report after generation? |
| 628 |
myReport$export(open = FALSE) |
| 629 |
``` |
| 630 |
|
| 631 |
# Capturing evaluation information with evals |
| 632 |
|
| 633 |
When working on the [rapport package](https://rapporter.github.io/rapport/), I really needed some nifty R function that can evaluate R expression along with capturing errors and warnings. Unfortunately the `evaluate` package had only limited features at that time, as it could not return the raw R object, but only the standard output with messages. So I wrote my own function, and soon some further feature requests arose, like identifying if an R expression results in a plot etc. This section aims to give a quick introduction to the functionality of `evals`, but for more usage/implementation details, please refer to specialized vignette, which can be accessed by `vignette('evals', package='pander')` or available online [here](https://rapporter.github.io/pander/evals.html). |
| 634 |
|
| 635 |
|
| 636 |
But probably it's easier to explain what `evals` can do with a simple example: |
| 637 |
|
| 638 |
```rout |
| 639 |
> evals('1:10') |
| 640 |
<%= paste(capture.output(evals('1:10')), collapse = '\n') %> |
| 641 |
``` |
| 642 |
|
| 643 |
So `evals` can evaluate a character vector of R expressions, and it returns a list of captured stuff while running those: |
| 644 |
|
| 645 |
* `src` holds the R expression, |
| 646 |
* `result` contains the raw R object as is, |
| 647 |
* `output` represents how the R object is printed to the standard output, |
| 648 |
* `type` is the `class` of the returned R object, |
| 649 |
* `msg` is a list of possible messages captured while running the R expression and |
| 650 |
* `stdout` contains if anything was written to the standard output. |
| 651 |
|
| 652 |
Besides capturing this nifty list of important circumstances, `evals` can automatically identify if an R expression is returning anything to a graphical device, and can save the resulting image in a variety of file formats along with some extra options, like applying a custom theme on base, `lattice` or `ggplot2` plots: |
| 653 |
|
| 654 |
```rout |
| 655 |
> evals('hist(mtcars$hp)')[[1]]$result |
| 656 |
<%= evals('hist(mtcars$hp)')[[1]]$result %> |
| 657 |
``` |
| 658 |
|
| 659 |
So instead of a captured R object (which would be `NULL` in this situation by the way), we get the path of the image where the plot was saved: |
| 660 |
|
| 661 |
 |
| 662 |
|
| 663 |
Well, this is not a standard histogram usually returned by the `hist` function, right? As mentioned before, `evals` have some extra features like applying the user defined theme on various plots automatically. Please see the `graphs.brew` example [above](#examples) for further details, or check the related [global options](#evals-options). If you do not like this feature, simply add `evalsOptions('graph.unify`, FALSE)` to your `.Rprofile`. |
| 664 |
|
| 665 |
|
| 666 |
Further features are described in the [technical docs](https://www.rdocumentation.org/packages/pander/functions/evals), and now I'll only give a brief introduction to another important feature of `evals`. |
| 667 |
|
| 668 |
## Caching |
| 669 |
|
| 670 |
As `pander::evals` is using a **custom caching algorithm** in the means of evaluating R expressions, it might be worthwhile to give a short summary of what is going on in the background when you are running e.g. [`Pandoc.brew`](#brew-to-pandoc), the ["live report generation"](#live-report-generation) engine or `evals` directly: |
| 671 |
|
| 672 |
* Each passed R chunk is `parse`d to single R expressions. |
| 673 |
* Each parsed expression's **part** (let it be a function, variable, constant etc.) is evaluated (as `name`) separately to a `list`. This list describes the unique structure *and* the content of the passed R expressions. This has some really great benefits (see below). |
| 674 |
* A **hash** is computed of each list element and *cached* too in `pander`'s local environments. This is useful if you are using large data frames, just imagine: the caching algorithm would have to compute the hash for the same data frame each time it's touched! This way the hash is recomputed only if the R object with the given name is changed. |
| 675 |
* The list of such R objects is serialized, then an `SHA-1` hash is computed, which is unique and there is no real risk of collision. |
| 676 |
* If [`evals`](#evals) can find the cached results in an environment of `pander`'s namespace (if `cache.mode` set to `enviroment` - see [below](#pander-options)) or in a file named to the computed hash (if `ċache.mode` set to `disk`), then it is returned on the spot. *The objects modified/created by the cached code are also updated.* |
| 677 |
* Otherwise the call is evaluated and the results and the modified R objects of the environment are optionally saved to cache (e.g. if `cache` is active *and* if the `proc.time()` of the evaluation is higher then it is defined in `cache.time` - see details in [evals' options](#evals-options)). |
| 678 |
|
| 679 |
<a id="in-practice"></a> |
| 680 |
|
| 681 |
As `pander` does not cache based on raw sources of chunks and there is no easy way of enabling/disabling caching on a chunk basis, the users have to live with some *great advantages* and some *minor tricky situations* - which latter cannot be solved theoretically in my opinion, but [I'd love to hear your feedback](https://github.com/Rapporter/pander/issues). |
| 682 |
|
| 683 |
The caching hash is computed based on the structure and **content** of the R commands instead of the used variable names or R expressions, so let us make some POC example to show the **greatest asset**: |
| 684 |
|
| 685 |
```r |
| 686 |
x <- mtcars$hp |
| 687 |
y <- 1e3 |
| 688 |
evals('sapply(rep(x, y), mean)') |
| 689 |
``` |
| 690 |
|
| 691 |
It took a while, huh? :) |
| 692 |
|
| 693 |
Let us create some custom functions and variables, which are not identical to the above call: |
| 694 |
|
| 695 |
```r |
| 696 |
f <- sapply |
| 697 |
g <- rep |
| 698 |
h <- mean |
| 699 |
X <- mtcars$hp * 1 |
| 700 |
Y <- 1000 |
| 701 |
``` |
| 702 |
|
| 703 |
And now try to run something like: |
| 704 |
|
| 705 |
```r |
| 706 |
evals('f(g(X, Y), h)') |
| 707 |
``` |
| 708 |
|
| 709 |
Yes, it was returned from cache! |
| 710 |
|
| 711 |
About the **kickback**: |
| 712 |
|
| 713 |
As `pander` (or rather: `evals`) does not really deal with what is written in the provided sources but rather checks what is **inside that**, there might be some tricky situations where you would expect the cache to work, but it would not. Short example: we are computing and saving to a variable something heavy in a chunk (please run these in a clean R session to avoid conflicts): |
| 714 |
|
| 715 |
```r |
| 716 |
evals('x <- sapply(rep(mtcars$hp, 1e3), mean)') |
| 717 |
``` |
| 718 |
|
| 719 |
It is cached, just run again, you will see. |
| 720 |
|
| 721 |
But if you would create `x` in your *global environment* with any value (which has nothing to do with the special environment of the report!) **and** `x` was not defined in the report before this call (**and** you had no `x` value in your global environment before), then the content of `x` would result in a new hash for the cache - so caching would not work. E.g.: |
| 722 |
|
| 723 |
```r |
| 724 |
x <- 'foobar' |
| 725 |
evals('x <- sapply(rep(mtcars$hp, 1e3), mean)') |
| 726 |
``` |
| 727 |
|
| 728 |
I really think this is a minor issue (with very special coincidences) which cannot be addressed cleverly - but **could be avoided with some cautions** (e.g. run `Pandoc.brew` in a clean R session like with `Rscript` or [`littler`](http://dirk.eddelbuettel.com/code/littler.html) - if you are really afraid of this issue). And after all: you loose nothing, just the cache would not work for that only line and only once in most of the cases. |
| 729 |
|
| 730 |
Other cases when the hash of a call will not match cached hashes: |
| 731 |
|
| 732 |
* a number is replaced by a variable holding the number, e.g.: `evals('1:5')` vs. `x <- 1:5;evals('x')` |
| 733 |
* a part of an R object is replaced by a variable holding that, e.g.: `evals('mean(mtcars$hp)')` vs. `x <- mtcars$hp;evals('mean(x)')` |
| 734 |
|
| 735 |
But the e.g. following do work from cache fine: |
| 736 |
|
| 737 |
``` |
| 738 |
x <- mtcars$hp |
| 739 |
xx <- mtcars$hp*1 |
| 740 |
evals('mean(x)') |
| 741 |
evals('mean(xx)') |
| 742 |
``` |
| 743 |
|
| 744 |
<a id='pander-options'></a><a id='panderoptions'></a> |
| 745 |
|
| 746 |
# General options |
| 747 |
|
| 748 |
The package comes with a variety of globally adjustable options, which have an effect on the result of your reports. You can query and update these options with the `panderOptions` function: |
| 749 |
|
| 750 |
* `digits`: numeric (default: `2`) passed to `format`. Can be a vector specifying values for each column (has to be the same length as number of columns). Values for non-numeric columns will be disregarded. |
| 751 |
* `decimal.mark`: string (default: `.`) passed to `format` |
| 752 |
* `formula.caption.prefix`: string (default: `Formula: `) passed to `pandoc.formula` to be used as caption prefix. Be sure about what you are doing if changing to other than `Formula: ` or `:`. |
| 753 |
* `big.mark`: string (default: ``) passed to `format` |
| 754 |
* `round`: numeric (default: `Inf`) passed to `round`. Can be a vector specifying values for each column (has to be the same length as number of columns). Values for non-numeric columns will be disregarded. |
| 755 |
* `keep.trailing.zeros`: boolean (default: `FALSE`) show or remove trailing zeros in numbers (e.g. in numeric vectors or in columns of tables with numeric values) |
| 756 |
* `keep.line.breaks`: boolean (default: `FALSE`) to keep or remove line breaks from cells in a table |
| 757 |
* `missing`: string (default: `NA`) to replace missing values in vectors, tables etc. |
| 758 |
* `date`: string (default: `'%Y/%m/%d %X'`) passed to `format` when printing dates (`POSIXct` or `POSIXt`) |
| 759 |
* `header.style`: `'atx'` or `'setext'` passed to `pandoc.header` |
| 760 |
* `list.style`: `'bullet'` (default), `'ordered'` or `'roman'` passed to `pandoc.list`. Please not that this has no effect on `pander` methods. |
| 761 |
* `table.style`: `'multiline'`, `'grid'` or `'simple'` passed to `pandoc.table` |
| 762 |
* `table.emphasize.rownames`: boolean (default: `TRUE`) if row names should be highlighted |
| 763 |
* `table.split.table`: numeric passed to `pandoc.table` and also affects `pander` methods. This option tells `pander` where to split too wide tables. The default value (`80`) suggests the conventional number of characters used in a line, feel free to change (e.g. to `Inf` to disable this feature) if you are not using a VT100 terminal any more :) |
| 764 |
* `table.split.cells`: numeric (default: 30) passed to `pandoc.table` and also affects pander methods. This option tells pander where to split too wide cells with line breaks. Set `Inf`` to disable. |
| 765 |
* `table.caption.prefix`: string (default: `Table: `) passed to `pandoc.table` to be used as caption prefix. Be sure about what you are doing if changing to other than `Table: ` or `:`. |
| 766 |
* `table.continues`: string (default: `Table continues below`) passed to `pandoc.table` to be used as caption for long (split) without a use defined caption |
| 767 |
* `table.continues.affix`: string (default: `(continued below)`) passed to `pandoc.table` to be used as an affix concatenated to the user defined caption for long (split) tables |
| 768 |
* `table.alignment.default`: string (default: `centre`) that defines the default alignment of cells. Can be `left`, `right` or `centre` that latter can be also spelled as `center` |
| 769 |
* `table.alignment.rownames`: string (default: `centre`) that defines the alignment of rownames in tables. Can be `left`, `right` or `centre` that latter can be also spelled as `center` |
| 770 |
* `use.hyphening`: boolean (default: `FALSE`) if try to use hyphening when splitting large cells according to table.split.cells. Requires `sylly` package. |
| 771 |
* `evals.messages`: boolean (default: `TRUE`) passed to `evals`' `pander` method specifying if messages should be rendered |
| 772 |
* `p.wrap`: a string (default:`'_'`) to wrap vector elements passed to `p` function |
| 773 |
* `p.sep`: a string (default: `', '`) with the main separator passed to `p` function |
| 774 |
* `p.copula`: a string (default: `'and'`) a string with ending separator passed to `p` function |
| 775 |
* `plain.ascii`: boolean (default: FALSE) to define if output should be in plain ascii or not |
| 776 |
* `graph.nomargin`: boolean (default: `TRUE`) if trying to keep plots' margins at minimal |
| 777 |
* `graph.fontfamily`: string (default: `'sans'`) specifying the font family to be used in images. Please note, that using a custom font on Windows requires `grDevices:::windowsFonts` first. |
| 778 |
* `graph.fontcolor`: string (default: `'black'`) specifying the default font color |
| 779 |
* `graph.fontsize`: numeric (default: `12`) specifying the *base* font size in pixels. Main title is rendered with `1.2` and labels with `0.8` multiplier. |
| 780 |
* `graph.grid`: boolean (default: `TRUE`) if a grid should be added to the plot |
| 781 |
* `graph.grid.minor`: boolean (default: `TRUE`) if a miner grid should be also rendered |
| 782 |
* `graph.grid.color`: string (default: `'grey'`) specifying the color of the rendered grid |
| 783 |
* `graph.grid.lty`: string (default: `'dashed'`) specifying the line type of grid |
| 784 |
* `graph.boxes`: boolean (default: `FALSE`) if to render a border around of plot (and e.g. around strip) |
| 785 |
* `graph.legend.position`: string (default: `'right'`) specifying the position of the legend: 'top', 'right', 'bottom' or 'left' |
| 786 |
* `graph.background`: string (default: `'white'`) specifying the plots main background's color |
| 787 |
* `graph.panel.background`: string (default: `'transparent'`) specifying the plot's main panel background. Please *note*, that this option is not supported with `base` graphics. |
| 788 |
* `graph.colors`: character vector of default color palette (defaults to a [colorblind theme](https://jfly.uni-koeln.de/color/)). Please *note* that this update work with `base` plots by appending the `col` argument to the call if not set. |
| 789 |
* `graph.color.rnd`: boolean (default: `FALSE`) specifying if the palette should be reordered randomly before rendering each plot to get colorful images |
| 790 |
* `graph.axis.angle`: numeric (default: `1`) specifying the angle of axes' labels. The available options are based on `par(les)` and sets if the labels should be: |
| 791 |
|
| 792 |
* `1`: parallel to the axis, |
| 793 |
* `2`: horizontal, |
| 794 |
* `3`: perpendicular to the axis or |
| 795 |
* `4`: vertical. |
| 796 |
|
| 797 |
* `graph.symbol`: numeric (default: `1`) specifying a symbol (see the `pch` parameter of `par`) |
| 798 |
* `knitr.auto.asis`: boolean (default: `TRUE`) if the results of `pander` should be considered as `asis` in `knitr`. Equals to specifying `results='asis'` in the R chunk, so thus there is no need to do so if set to `TRUE`. |
| 799 |
|
| 800 |
<a id='evals-options'></a><a id='evalsoptions'></a> |
| 801 |
|
| 802 |
Besides localization of numeric formats or the styles of tables, lists and plots, there are some technical options as well, which would effect e.g. [caching](#caching) or the format of rendered image files. You can query/update those with the `evalsOptions` function as the main backend of `pander` calls is a custom evaluation function called [`evals`](#evals). |
| 803 |
|
| 804 |
The list of possible options are: |
| 805 |
|
| 806 |
* `parse`: if `TRUE` the provided `txt` elements would be merged into one string and parsed to logical chunks. This is useful if you would want to get separate results of your code parts - not just the last returned value, but you are passing the whole script in one string. To manually lock lines to each other (e.g. calling a `plot` and on next line adding an `abline` or `text` to it), use a plus char (`+`) at the beginning of each line which should be evaluated with the previous one(s). If set to `FALSE`, [`evals`](#evals) would not try to parse R code, it would get evaluated in separate runs - as provided. Please see the documentation of [`evals`](#evals). |
| 807 |
* `cache`: [caching](#caching) the result of R calls if set to `TRUE` |
| 808 |
* `cache.mode`: cached results could be stored in an `environment` in _current_ R session or let it be permanent on `disk`. |
| 809 |
* `cache.dir`: path to a directory holding cache files if `cache.mode` set to `disk`. Default set to `.cache` in current working directory. |
| 810 |
* `cache.time`: number of seconds to limit caching based on `proc.time`. If set to `0`, all R commands, if set to `Inf`, none is cached (despite the `cache` parameter). |
| 811 |
* `cache.copy.images`: copy images to new file names if an image is returned from the *disk* cache? If set to `FALSE` (default), the cached path would be returned. |
| 812 |
* `classes`: a vector or list of classes which should be returned. If set to `NULL` (by default) all R objects will be returned. |
| 813 |
* `hooks`: list of hooks to be run for given classes in the form of `list(class = fn)`. If you would also specify some parameters of the function, a list should be provided in the form of `list(fn, param1, param2=NULL)` etc. So the hooks would become `list(class1=list(fn, param1, param2=NULL), ...)`. See example of [`evals`](#evals) for more details. A default hook can be specified too by setting the class to `'default'`. This can be handy if you do not want to define separate methods/functions to each possible class, but automatically apply the default hook to all classes not mentioned in the list. You may also specify only one element in the list like: `hooks=list('default' = pander_return)`. Please note, that nor error/warning messages, nor stdout is captured (so: updated) while running hooks! |
| 814 |
* `length`: any R object exceeding the specified length will not be returned. The default value (`Inf`) does not filter out any R objects. |
| 815 |
* `output`: a character vector of required returned values. This might be useful if you are only interested in the `result`, and do not want to save/see e.g. `messages` or `print`ed `output`. See examples of [`evals`](#evals). |
| 816 |
* `graph.unify`: should `evals` try to unify the style of (`base`, `lattice` and `ggplot2`) plots? If set to `TRUE`, some `panderOptions()` would apply. By default this is disabled not to freak out useRs :) |
| 817 |
* `graph.name`: set the file name of saved plots which is `%s` by default. A simple character string might be provided where `%d` would be replaced by the index of the generating `txt` source, `%n` with an incremented integer in `graph.dir` with similar file names and `%t` by some unique random characters. When used in a `brew` file, `%i` is also available which would be replaced by the chunk number. |
| 818 |
* `graph.dir`: path to a directory where to place generated images. If the directory does not exist, [`evals`](#evals) try to create that. Default set to `plots` in current working directory. |
| 819 |
* `graph.output`: set the required file format of saved plots. Currently it could be any of `grDevices`: `png`, `bmp`, `jpeg`, `jpg`, `tiff`, `svg` or `pdf`. Set to `NA` not to save plots at all and tweak that setting with `capture.plot()` on demand. |
| 820 |
* `width`: width of generated plot in pixels for even vector formats |
| 821 |
* `height`: height of generated plot in pixels for even vector formats |
| 822 |
* `res`: nominal resolution in `ppi`. The height and width of vector images will be calculated based in this. |
| 823 |
* `hi.res`: generate high resolution plots also? If set to `TRUE`, each R code parts resulting an image would be run twice. |
| 824 |
* `hi.res.width`: width of generated high resolution plot in pixels for even vector formats. The `height` and `res` of high resolution image is automatically computed based on the above options to preserve original plot aspect ratio. |
| 825 |
* `graph.env`: save the environments in which plots were generated to distinct files (based on `graph.name`) with `env` extension? |
| 826 |
* `graph.recordplot`: save the plot via `recordPlot` to distinct files (based on `graph.name`) with `recodplot` extension? |
| 827 |
* `graph.RDS` save the raw R object returned (usually with `lattice` or `ggplot2`) while generating the plots to distinct files (based on `graph.name`) with `RDS` extension? |
| 828 |
* `log`: `NULL` or an optionally passed *namespace* for `logger` to record all info, trace, debug and error messages. |
| 829 |
|
| 830 |
# Difference from other rendering packages |
| 831 |
|
| 832 |
How does `pander` differ from Sweave, brew, knitr, R2HTML and the other tools of literate programming? First of all `pander` can be used as a helper with any other literate programming solution, so **you can call `pander` inside of `knitr` chunks**. |
| 833 |
|
| 834 |
|
| 835 |
But if you stick with `pander`'s literate programming engine, then there's not much need for calling `ascii`, `xtable`, `Hmisc`, `tables` etc. or even `pander` in the R command chunks to **transform R objects** into markdown, HTML, tex etc. as `Pandoc.brew` automatically results in Pandoc's markdown, which can be converted to almost any text document format. Conversion can be done automatically after calling `pander` reporting functions ([Pander.brew](#brew-to-pandoc) or [Pandoc](#live-report-generation)). |
| 836 |
|
| 837 |
Based on the fact that `pander` transforms R objects into markdown, **no "traditional" R console output is shown** in the resulting document (nor in markdown, nor in exported docs), but **all R objects are transformed to tables, list etc**. Well, there is an option (`show.src`) to show the original R commands before the formatted output, and `pander` calls can be also easily tweaked to return the printed version of the R objects - if you would need that in some strange situation - like writing an R tutorial. But really think that nor R code, nor raw R results have anything to do with an exported report. |
| 838 |
|
| 839 |
Of course **all warnings, messages and errors are captured** while evaluating R expressions just like `stdout` besides the **raw R objects**. So the resulting report also includes the raw R objects for further edits if needed - which is a very unique feature. |
| 840 |
|
| 841 |
**Graphs and plots are automatically identified** in code chunks and saved to disk in a `png` file linked in the resulting document. This means that if you create a report (e.g. `brew` a text file) and export it to PDF/docx etc. all the plots/images would be there. There are some parameters to specify the resolution of the image and also the type (e.g. `jpg`, `svg` or `pdf`) besides a **wide variety of [theme options](#pander-options)**. About the latter, please check the `graphs.brew` example [above](#examples). |
| 842 |
|
| 843 |
And `pander` uses its built-in (IMHO quite decent) [**caching**](#caching) engine. This means that if the evaluation of some R commands takes too long time (which can be set by option/parameter), then the results are saved in a file and returned from there on next similar R code's evaluation. This caching algorithm tries to be smart, as it not only checks the passed R sources, but the content of all variables and functions, and saves the hash of those. This is a quite secure way of caching (see details [above](#caching)), but if you would encounter any issues, just switch off the cache. I've not seen any issues for years :) |
| 844 |
|
| 845 |
# ESS |
| 846 |
|
| 847 |
I have created some simple LISP functions which would be handy if you are using the best damn IDE for R. These functions and default key-bindings are [shipped with the package](https://github.com/Rapporter/pander/blob/master/inst/pander.el), feel free to personalize. |
| 848 |
|
| 849 |
As time passed these small functions grew heavier (with my Emacs knowledge) so I ended up with a small library: |
| 850 |
|
| 851 |
## pander-mode |
| 852 |
|
| 853 |
I am currently working on `pander-mode` which is a small *minor-mode* for Emacs. There are a few (but useful) functions with default keybindings: |
| 854 |
|
| 855 |
* `pander-brew` (`C-c p b`): Run `Pandoc.brew` on current buffer or region (if mark is active), show results in *ess-output* and (optionally) copy results to clipboard while setting working directory to `tempdir()` temporary. |
| 856 |
* `pander-brew-export` (`C-c p B`): Run `Pandoc.brew` on current buffer or region (if mark is active) and export results to specified (auto-complete in minibuffer) format. Also tries to open exported document. |
| 857 |
* `pander-eval` (`C-c p e`): Run `pander` on (automatically evaluated) region *or* current chunk (if marker is not set), show results (of last returned R object) in `*ess-output*` and (optionally) copy those to clipboard while setting working directory to `tempdir()` temporary. |
| 858 |
|
| 859 |
Few options of `pander-mode`: `M-x customize-group pander` |
| 860 |
|
| 861 |
* `pander-clipboard`: If non-nil then the result of `pander-*` functions would be copied to clipboard. |
| 862 |
* `pander-show-source`: If non-nil then the source of R commands would also show up in generated documents while running 'pander-eval'. This would not affect `brew` functions ATM. |
| 863 |
|
| 864 |
To use this small lib, just type: `M-x pander-mode` on any document. It might be useful to add a hook to `markdown-mode` if you find this useful. |
| 865 |
|
| 866 |
<script type="text/javascript"> |
| 867 |
$(document).ready(function() { |
| 868 |
$('#logo').empty(); |
| 869 |
$('img[src="https://travis-ci.org/Rapporter/pander.png?branch=master"]').css('border', 'none').css('padding', '0px').parent().parent().css('text-align', 'justify'); |
| 870 |
$('img[src="https://coveralls.io/repos/Rapporter/pander/badge.svg?branch=master"]').css('border', 'none').css('padding', '0px').parent().parent().css('text-align', 'justify'); |
| 871 |
$('nav').css('height', '100%'); |
| 872 |
$("img").unbind("click"); |
| 873 |
}); |
| 874 |
</script> |
| 875 |
<a href="https://github.com/Rapporter/pander"><img style="position: fixed; top: -5px; right: -5px; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> |