0

I used to think that the results = "asis" chunk option is needed to include any chunk output verbatim in the rendered Rmarkdown document; otherwise the output would be formatted as console output (e.g. with leading ##).

However, several functions such as knitr::kable() seem to work just fine even without the results = "asis" option whereas the table I created manually is formatted as console output in the example below.

How does knitr know that the output is verbatim markdown and should be embedded as such?

My example:

---
title: Title
output: github_document
---

```{r}
# works without results = "asis"
knitr::kable(mtcars)
```

```{r}
# without results = "asis": formatted as console output
table <- "|col1|col2|\n|-|-|\n|a|b|"
writeLines(table)
```

```{r, results='asis'}
# works only with results = "asis"
writeLines(table)
```
dufei
  • 2,166
  • 1
  • 7
  • 18

1 Answers1

1

results = 'asis' tells knitr to not wrap code chunk output in a code block.

In your example 2, the output gets formatted as a code block (since there is no results = 'asis'):

## |col1|col2|
## |-|-|
## |a|b|

Example 3 treats the output 'as-is', which is valid markdown for formatting a table.

enter image description here

Some additonal examples are given in the R Markdown Cookbook.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • But why does it work in the first example even without `results = "asis"`? Examples 2 and 3 represent how I thought this chunk option worked. – dufei Nov 07 '21 at 12:30
  • That is because of `pandoc` correctly recognising the pipe table generated through `kable` (which is the default `kable` output format). Mind you, this only works if `kable` is the top-level expression in your code block. There are a lot of posts here on Stack Overflow and on GH that revolve around this "feature" and that usually lead to the need to include `result = 'asis'` in expressions including nested `kable` calls or loops: see e.g. [here](https://github.com/yihui/knitr/issues/1109), [here](https://stackoverflow.com/questions/48118052/rmarkdown-not-producing-table-within-for-in-loop). – Maurits Evers Nov 07 '21 at 12:57
  • Then I'd be curious to see what `knitr` outputs (i.e. before pandoc converts the markdown flavor to that of GitHub)... apparently there is no `keep_md` option when exporting as `github_document`. – dufei Nov 07 '21 at 13:47