5
votes

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?

1
So are you just trying to remove the "##" from the output?MrFlick
No, I want the newline from the function to be shown in the html outputTheodor
By "shown" you mean you literally want to see "\n" rather than get a new line?MrFlick
Sorry, I mean: I want to obtain "hello!" and "1 2" on different rows. In a similar way as would appear in the R consoleTheodor
Which is what the results without "asis" does, but you just don't want it to also draw the "##"? Are you rendering to html? pdf?MrFlick

1 Answers

10
votes

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.