Embed Diffs in R Markdown

library(diffobj)

Basic Requirements

Any R chunks that produce diffs should include the results='asis' option, e.g.:

```{r results='asis'}
# R code here
```

Easy but Ugly

This is what a basic code block should look like:

```{r results='asis'}
cat(                                 # output to screen
  as.character(                      # convert to diff to character vector
    diffPrint(                       # run diff
      1:5, 2:6,
      format="html",                 # specify html output
      style=list(
        html.output="diff.w.style"   # configure html style
      )
) ) )
```

Here we use this same code as an actual markdown R code block:

cat(
  as.character(
    diffPrint(
      1:5, 2:6,
      format="html",
      style=list(html.output="diff.w.style")
) ) )

This is an ugly implementation because it produces illegal HTML. The styles are directly embedded in the body of the document, outside of the HEAD tags. Although this is illegal HTML, it seems to work in most browsers. Another problem is that every diff you use in your document will inject the same CSS code over and over.

A Cleaner Option

A better option is to provide the CSS directly by modifying the output portion of the YAML header:

---
output:
    rmarkdown::html_vignette:
        toc: true
        css: !expr diffobj::diffobj_css()
---

In reality you will probably want to specify multiple CSS files, including the original rmarkdown one:

---
output:
    rmarkdown::html_vignette:
        toc: true
        css:
          - !expr diffobj::diffobj_css()
          - !expr system.file("rmarkdown", "templates", "html_vignette", "resources", "vignette.css", package = "rmarkdown")
---

Once you set this up then you can use:

cat(
  as.character(
    diffPrint(
      1:5, 2:6,
      format="html",
      style=list(html.output="diff.only")   # notice this changed
) ) )

This will omit the CSS, but since we include it via the YAML everything should work as expected.

Use Options

Almost all diffobj parameters can be specified via options:

options(
  diffobj.format="html",
  diffobj.style=list(html.output="diff.only")
)
old.opts <- options(
  diffobj.format="html",
  diffobj.style=list(html.output="diff.only")
)

Then you can just run the diff as normal:

cat(as.character(diffPrint(1:5, 2:6)))
options(old.opts)


Try the diffobj package in your browser

Any scripts or data that you put into this service are public.

diffobj documentation built on July 29, 2018, 5:01 p.m.