Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show formatted R output with results='asis' in rmarkdown

Is there a way of showing formatter R output in rmarkdown/knitr when using results = 'asis'?

An example would be the following function:

myfun <- function() {
  cat("hello!\n")
  cat(c("one" = 1, "two" = 2))
}

Then, this chunk will print the second cat on a new row:

```{r}
myfun()
```

nice printing

But this will ignore the formatting from myfun:

```{r, results = "asis"}
myfun()
```

non-formatted printing

Is there a way of keeping results='asis' but at the same time keep the output of myfun formatted as intended?

like image 775
Theodor Avatar asked Oct 03 '18 16:10

Theodor


People also ask

What output formats are available with R Markdown?

The following output formats are available to use with R Markdown. You can also build books, websites, and interactive documents with R Markdown. Each output format is implemented as a function in R.

What can you do with R Markdown?

You can also build books, websites, and interactive documents with R Markdown. Each output format is implemented as a function in R. You can customize the output by passing arguments to the function as sub-values of the output field.

How do I render a markdown file with RStudio IDE?

The header of 1-example.Rmd shows that it renders to an HTML file by default. The RStudio IDE knit button renders a file to the first format listed in its output field. You can render to additional formats by clicking the dropdown menu beside the knit button: The following output formats are available to use with R Markdown.

How do I change the output format in R?

Output Options. Each output format is implemented as a function in R. You can customize the output by passing arguments to the function as sub-values of the output field. For example, 8-outputs.Rmd would render with a floating table of contents.


1 Answers

You can use the knitr chunk option results = "asis" if you are happy to add two or more spaces at the end of the line. That is, instead of "hello\n", you need to write "hello \n" to trigger the line break.

Example R Markdown code:

---
output: html_document
---

```{r}
myfun <- function() {
  cat("hello!  \n")
  cat(c("one" = 1, "two" = 2))
}
```

```{r results = "asis"}
myfun()
```

Gives

output on two lines

Why the blank spaces? It's because two spaces at the end of a line are used to indicate a hard line break in markdown. For example, this quote is taken from Pandoc's Markdown (which is the default markdown flavour R Markdown uses):

Paragraphs
A paragraph is one or more lines of text followed by one or more blank lines. Newlines are treated as spaces, so you can reflow your paragraphs as you like. If you need a hard line break, put two or more spaces at the end of a line.

like image 83
markdly Avatar answered Oct 10 '22 23:10

markdly