如何在 rmarkdown 中使用 results='asis' 显示格式化的 R 输出
How to show formatted R output with results='asis' in rmarkdown
当使用 results = 'asis' 时,有没有办法在 rmarkdown/knitr 中显示格式化程序 R 输出?
例如以下函数:
myfun <- function() {
cat("hello!\n")
cat(c("one" = 1, "two" = 2))
}
然后,此块将在新行上打印第二个 cat
:
```{r}
myfun()
```
但这会忽略来自 myfun
:
的格式
```{r, results = "asis"}
myfun()
```
有没有办法在保持 results='asis'
的同时保持 myfun
的输出格式符合预期?
如果您愿意在行尾添加两个或更多空格,则可以使用 knitr 块选项 results = "asis"
。也就是说,您需要编写 "hello \n"
而不是 "hello\n"
来触发换行符。
示例 R Markdown 代码:
---
output: html_document
---
```{r}
myfun <- function() {
cat("hello! \n")
cat(c("one" = 1, "two" = 2))
}
```
```{r results = "asis"}
myfun()
```
给予
为什么是空格?这是因为行尾的两个空格用于表示 markdown 中的硬换行符。例如,这句话取自 Pandoc's Markdown(这是 R Markdown 使用的默认降价风格):
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.
当使用 results = 'asis' 时,有没有办法在 rmarkdown/knitr 中显示格式化程序 R 输出?
例如以下函数:
myfun <- function() {
cat("hello!\n")
cat(c("one" = 1, "two" = 2))
}
然后,此块将在新行上打印第二个 cat
:
```{r}
myfun()
```
但这会忽略来自 myfun
:
```{r, results = "asis"}
myfun()
```
有没有办法在保持 results='asis'
的同时保持 myfun
的输出格式符合预期?
如果您愿意在行尾添加两个或更多空格,则可以使用 knitr 块选项 results = "asis"
。也就是说,您需要编写 "hello \n"
而不是 "hello\n"
来触发换行符。
示例 R Markdown 代码:
---
output: html_document
---
```{r}
myfun <- function() {
cat("hello! \n")
cat(c("one" = 1, "two" = 2))
}
```
```{r results = "asis"}
myfun()
```
给予
为什么是空格?这是因为行尾的两个空格用于表示 markdown 中的硬换行符。例如,这句话取自 Pandoc's Markdown(这是 R Markdown 使用的默认降价风格):
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.