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

 ̄綄美尐妖づ 提交于 2020-06-15 06:27:27

问题


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()
```

But this will ignore the formatting from myfun:

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

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


回答1:


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

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.



来源:https://stackoverflow.com/questions/52631689/how-to-show-formatted-r-output-with-results-asis-in-rmarkdown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!