pander R Package

repository·master·Indexed 43 days ago

https://github.com/rapporter/pander

An R package designed to render R objects into Pandoc's markdown format. It provides tools for creating markdown reports, exporting complex documents to PDF, DOCX, and HTML via Pandoc, and includes the pander() S3 generic method for converting data frames, matrices, and statistical model outputs (e.g., lm, glm, aov, t.test) into markdown.

Tokens
10.6K
Snippets
23
Records
37
Agent score
5%

What's inside pander

  1. How pander differs from other literate programming tools

    master

    Unlike traditional tools like Sweave, knitr, or R2HTML, pander is designed to be a helper that can be called inside other literate programming solutions (e.g., inside knitr chunks).

    Key characteristics include:

    • Automatic Markdown Transformation: Pandoc.brew automatically results in Pandoc's markdown, which can be converted to almost any text format.
    • Object-to-Markdown Conversion: Instead of showing raw R console output, pander transforms R objects into formatted tables, lists, etc.
    • Source Control: By default, raw R code and results are not shown in the exported document, but you can use the show.src option to include the original R commands.
    • Error/Warning Capture: All warnings, messages, and errors are captured during R expression evaluation.
    • Automatic Plot Handling: Graphs and plots are automatically identified in code chunks, saved as png files (or other specified types like jpg, svg, or pdf), and linked in the resulting document.
    • Smart Caching: pander includes a built-in caching engine that hashes the R source, variable content, and function content to skip re-evaluating long-running commands.
  2. Create complex Pandoc documents from R

    master

    There are three primary ways to generate reports using pander:

    1. Markdown to Multiple Formats: Create a markdown text file (using brew, knitr, or custom scripts) and use Pandoc.convert to transform it into formats like HTML, ODT, PDF, or DOCX. This acts as a wrapper around Pandoc.
    2. Literate Programming with Pandoc.brew: Use a syntax similar to brew to include R code chunks directly in your document. Pandoc.brew automatically handles the conversion of R objects to markdown, allowing you to generate beautiful reports in multiple formats without manual transformation.
    3. Live Report Generation: Build a report dynamically during an active R session by adding R objects and text paragraphs to a Pandoc reference class object.
  3. How pander's caching mechanism works

    master

    The pander::evals function uses a custom caching algorithm to speed up the evaluation of R expressions. Instead of caching based on the raw source code of a chunk, it caches based on the structure and content of the R expressions.

    How it works:

    1. Parsing: Each R chunk is parsed into single R expressions.
    2. Structural Analysis: Each part of the expression (functions, variables, constants) is evaluated to a list describing its unique structure and content.
    3. Hashing: A hash is computed for each list element. For large objects like data frames, the hash is only recomputed if the R object's name or content changes, preventing expensive re-computations.
    4. Unique Identifier: An SHA-1 hash is computed from the serialized list of these objects to create a unique identifier.
    5. Cache Lookup:
      • If cache.mode is set to environment, evals looks for results in pander's namespace.
      • If cache.mode is set to disk, evals looks for a file named after the computed hash.
    6. Execution: If a cache hit occurs, the result is returned immediately (including updates to objects modified/created by the cached code). Otherwise, the expression is evaluated, and results are optionally saved to the cache if the evaluation time exceeds cache.time.
    # Example of cache hit due to structural/content similarity
    x <- mtcars$hp
    y <- 1e3
    evals('sapply(rep(x, y), mean)')
    
    # Even with different variable names, if the content/structure matches, it hits the cache:
    f <- sapply
    g <- rep
    h <- mean
    X <- mtcars$hp * 1
    Y <- 1000
    
    evals('f(g(X, Y), h)') # This returns from cache
  4. Use Pandoc.brew for template-based report generation

    master

    The Pandoc.brew function allows you to generate Pandoc-formatted markdown from text files containing special brew tags. This is useful for creating reports where R code is embedded directly in text.

    Supported Tags

    • <% ... %>: Runs inline R commands (similar to standard brew).
    • <%= ... %>: Runs R commands and applies pander to the returned object, converting it into Pandoc markdown. This handles plots, images, warnings, and errors automatically.

    Key Features

    • Automatic Image Handling: Plots and images are rendered to png files and converted into Pandoc markdown image links.
    • Error/Warning Capture: All warnings, messages, and errors are recorded and returned as footnotes or inline messages.
    • Caching: Heavy R commands (evaluating for > 0.1s) are cached to speed up subsequent report generation.
    • Structured Returns: Unlike the original brew package, Pandoc.brew returns a structured list containing both the rendered text and the evaluated R objects, which is useful for post-processing.
    # Basic usage (outputs to stdout)
    Pandoc.brew(system.file('README.brew', package = 'pander'))
    
    # Exporting to specific formats (e.g., HTML or PDF)
    Pandoc.brew(text = text, output = tempfile(), convert = 'html')
    Pandoc.brew(text = text, output = tempfile(), convert = 'pdf')
  5. Install the pander package

    master

    You can install the stable version of pander from CRAN using the standard R installation command. For the latest development version with new features and fixes, install it directly from GitHub using devtools.

    # Install stable version from CRAN
    install.packages('pander')
    
    # Install development version from GitHub
    devtools::install_github('Rapporter/pander')
  6. Install Pandoc for document conversion

    master

    While pander functions work without Pandoc (e.g., for rendering R objects to markdown in the console), you must have Pandoc pre-installed if you want to convert your generated markdown reports into other formats like PDF, docx, or HTML.

    Note: RStudio (v0.98.932+) includes a bundled Pandoc binary. If you are not using RStudio, download the binary from the official Pandoc website and restart your R session to update your PATH.

  7. Use pander-mode in Emacs

    master

    For users of the Emacs IDE with ESS, pander-mode provides specialized commands to run pander operations on buffers or regions.

    To enable the mode, run M-x pander-mode in your document. You can also add it to a hook, such as markdown-mode.

    Commands

    • pander-brew (C-c p b): Runs Pandoc.brew on the current buffer or selected region. Results are shown in *ess-output* and can optionally be copied to the clipboard.
    • pander-brew-export (C-c p B): Runs Pandoc.brew on the current buffer or region and exports the results to a specified format (via minibuffer autocomplete). It attempts to open the exported document automatically.
    • pander-eval (C-c p e): Runs pander on the selected region or the current chunk. Results are shown in *ess-output* and can optionally be copied to the clipboard.

    Configuration

    Use M-x customize-group pander to adjust settings:

    • pander-clipboard: If set to non-nil, pander-* function results are automatically copied to the clipboard.
    • pander-show-source: If set to non-nil, the source of R commands is included in generated documents when using pander-eval (note: this does not currently affect brew functions).
  8. Use pander in literate programming workflows

    master

    Unlike traditional tools like Sweave or knitr that show raw R console output, pander transforms R objects directly into Markdown, HTML, or LaTeX.

    Key Features:

    • Integration: You can call pander() inside knitr chunks.
    • Automatic Transformation: All R objects are converted to formatted tables, lists, etc. Raw console output is not shown unless explicitly requested.
    • Capture: All warnings, messages, and errors are captured during evaluation.
    • Graph Handling: Plots are automatically identified, saved to disk (e.g., as .png), and linked in the resulting document.
  9. Configure pander caching modes

    master

    You can control where pander::evals stores and retrieves cached results using the cache.mode option.

    • cache.mode = 'environment': Results are stored and retrieved from an environment within the pander namespace.
    • cache.mode = 'disk': Results are stored in files named after the computed SHA-1 hash on the local disk.
  10. Configure evals() plot themes

    master

    By default, evals() can automatically apply unified themes to plots (base, lattice, or ggplot2).

    To disable this automatic theme unification, add the following to your .Rprofile:

    evalsOptions('graph.unify', FALSE)
  11. How pander's caching engine works

    master

    The evals engine uses a sophisticated caching mechanism based on the content and structure of R expressions rather than just the raw source code.

    How it works:

    1. Parsing: Each R chunk is parsed into single R expressions.
    2. Hashing: A hash is computed for each parsed expression's parts (functions, variables, constants, etc.). This ensures that if the underlying data (e.g., a large data frame) hasn't changed, the hash remains the same.
    3. Retrieval: If cache.mode is set to environment, results are retrieved from pander's namespace. If set to disk, results are retrieved from a file named after the computed SHA-1 hash.
    4. Invalidation: The cache is bypassed if the R objects involved have changed or if the structure of the command differs.

    Key Behaviors:

    • Smart Matching: Different variable names that point to the same content will still trigger a cache hit. For example, evals('f(g(X, Y), h)') will hit the cache if the underlying functions and values of X and Y match a previous call, even if the names were previously x and y.
    • Cache Misses: Caching will fail if you replace a literal with a variable (e.g., evals('1:5') vs x <- 1:5; evals('x')) or if a variable in the global environment conflicts with a variable expected to be defined within the report's special environment.
    # Example of cache hit due to content matching
    x <- mtcars$hp
    y <- 1e3
    evals('sapply(rep(x, y), mean)')
    
    # Even with different names, this hits the cache:
    f <- sapply
    g <- rep
    h <- mean
    X <- mtcars$hp * 1
    Y <- 1000
    evals('f(g(X, Y), h)')
  12. Use the generic pander method

    master

    The pander() (or pandoc()) function is an S3 generic method that automatically detects the class of an R object and applies the appropriate rendering logic. It supports a wide range of classes including data.frame, matrix, list, lm, anova, glm, summary, and many more from statistical packages.

    # Automatically renders based on object class
    pander(mtcars[1:3, 1:3])
    pander(lm(mpg ~ hp, data = mtcars))
    pander(summary(lm(mpg ~ hp, data = mtcars)))