Knitr with asciidoc
For simple reports, I’m satisfied with R Markdown, but for a long report with a lot of sections, it’s nice to have a sidebar with a floating table of contents. (See this example and its AsciiDoc source.)
An important part of the appeal of Markdown is the limited set of simple marks. But sometimes you want just a little bit extra, like subscripts (e.g., in describing an F1 hybrid). You can insert a bit of html code, but it’s even better to use a similar system with a more rich syntax, like AsciiDoc.
Code chunk delimiters
knitr-wise, the main difference when you use asciidoc is that the code chunks are delimited differently. Here’s an example:
We see that this is an intercross with +r nind(sug)+ individuals. There are +r nphe(sug)+ phenotypes, and genotype data at +r totmar(sug)+ markers across the +r nchr(sug)+ autosomes. The genotype data is quite complete. Use +plot()+ to get a summary plot of the data. //begin.rcode summary-plot, fig.height=8 plot(sug) //end.rcode
The larger code chunks are delimited with
The in-line code chunks are indicated with
+, as AsciiDoc
+ to mark code, to be shown in a monospace font.
Otherwise, everything about the code chunks and chunk options is the same as with R Markdown.
Floating table of contents and other stuff
The top of my AsciiDoc example is the following:
An example Knitr/Asciidoc document ================================== link:https://kbroman.org[Karl W Broman] :toc2: :numbered: :data-uri:
:toc2: indicates to include a table of contents, floating in the
:numbered: indicates to number the sections.
:data-uri: indicates to embed the images within the html file.
You can’t use
xtable with AsciiDoc. Instead, use the
ascii function in the
which has a shocking number of arguments.
Here’s a simple example:
//begin.rcode table, results="asis", warning=FALSE x <- rnorm(100, 10, 5) y <- 2*x + rnorm(100, 0, 2) out <- lm(y ~ x) coef_tab <- summary(out)$coef library(ascii) ascii(coef_tab, include.rownames=TRUE, include.colnames=TRUE, header=TRUE) //end.rcode
Note the use of
results="asis". I used
warning=FALSE to suppress a
To use AsciiDoc, you’ll need to install AsciiDoc; see this installation page.
On Mac OSX, I recommend using Homebrew; then you
brew install asciidoc.
For older versions of asciidoc, you needed Python 2 and not Python 3.
On my computer,
python is Python 3; I used to have to switch to Python 2
before running AsciiDoc. If I forgot to switch, I would get the following
File "/usr/local/bin/asciidoc", line 101 except KeyError, k: raise AttributeError, k ^ SyntaxError: invalid syntax
Converting AsciiDoc to html
RStudio has no facilities for AsciiDoc; you’ll need to use command-line tools.
You first use
knit in the knitr package to process the asciidoc/knitr
R -e 'library(knitr);knit("knitr_example.Rasciidoc", "knitr_example.asciidoc")'
You then use
asciidoc to convert this to an html file: