In reproducing Jenny Bryan’s article on including verbatim R chunks in R Markdown (Rmd) scripts, I initially forgot John Gruber’s markdown basics for verbatim code output:
To specify an entire block of pre-formatted code, indent every line of the block by 4 spaces or 1 tab. Just like with code spans, &, <, and > characters will be escaped automatically.
Jenny collected several methods for including verbatim R code in an R Markdown script. To reproduce them, every line of each example must start with 4 spaces or a tab.
Here I modify just one of them, the suggestion from Karl Broman, involving <pre> and <code> tags, and got some interesting results. First, I add class=“r” to the <pre> tag to add shading to the output box. Next, I surround the final three back ticks with their own <code></code> pair.
<pre class="r"><code>```{r whatever}
data(cars)
summary(cars)
<code>```</code>
</code></pre>
The cool thing here is the effect of tabs on the HTML output. My Rmd file has the lines of code shown above. If I add a tab at the beginning of each line, the boxed output above is the output—the type of output useful for authors using Rmd to write about using Rmd (like I am now).
If I delete the tab that starts every line, the opening and closing <pre><code> tags produce the verbatim output in between—output suitable for Rmd users,
```{r whatever}
data(cars)
summary(cars)
```
Same script, with and without leading tabs.
Of course, we always have the option of not telling the reader how to enclose the R code at all, typing this in our Rmd,
```{r echo=TRUE}
data(cars)
summary(cars)
```
producing this output for the reader,
data(cars)
summary(cars)
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
leaving the reader free to copy the R code into the script of their choosing, e.g., Rnw, Rmd, or the console.
Leave a Reply
You must be logged in to post a comment.