在R Markdown中为代码块添加换行符

sus*_*joh 17 markdown r knitr

我正在使用带有R Markdown的knitr包来创建HTML报告.使用'+'时,我在将代码保持在单独的行上时遇到了一些麻烦.

例如,

```{r}
ggplot2(mydata, aes(x, y)) +
   geom_point()
```
Run Code Online (Sandbox Code Playgroud)

将返回以下HTML文档

ggplot2(mydata, aes(x, y)) + geom_point()
Run Code Online (Sandbox Code Playgroud)

通常情况下这很好,但是一旦我开始添加其他行,就会出现问题,我希望将这些行分开以使代码更容易理解.运行以下内容:

```{r}
ggplot2(mydata, aes(x, y)) +
   geom_point() +
   geom_line() +
   opts(panel.background = theme_rect(fill = "lightsteelblue2"),
        panel.border = theme_rect(col = "grey"),
        panel.grid.major = theme_line(col = "grey90"),
        axis.ticks = theme_blank(),
        axis.text.x  = theme_text (size = 14, vjust = 0),
        axis.text.y  = theme_text (size = 14, hjust = 1.3))
```
Run Code Online (Sandbox Code Playgroud)

将导致所有代码出现在一行中,使得更难以遵循:

ggplot2(mydata, aes(x, y)) + geom_point() + geom_line() + opts(panel.background = theme_rect(fill = "lightsteelblue2"), panel.border = theme_rect(col = "grey"), panel.grid.major = theme_line(col = "grey90"), axis.ticks = theme_blank(), axis.text.x  = theme_text (size = 14, vjust = 0), axis.text.y  = theme_text (size = 14, hjust = 1.3))
Run Code Online (Sandbox Code Playgroud)

任何帮助解决这个问题将不胜感激!

koh*_*ske 19

尝试块选项tidy = FALSE:

```{r tidy=FALSE}
ggplot2(mydata, aes(x, y)) +
  geom_point() +
  geom_line() +
  opts(panel.background = theme_rect(fill = "lightsteelblue2"),
       panel.border = theme_rect(col = "grey"),
       panel.grid.major = theme_line(col = "grey90"),
       axis.ticks = theme_blank(),
       axis.text.x  = theme_text (size = 14, vjust = 0),
       axis.text.y  = theme_text (size = 14, hjust = 1.3))
```
Run Code Online (Sandbox Code Playgroud)

  • 是的,IIRC`opts_chunk $ set(tidy = FALSE)` (2认同)
  • 人力资源管理.如果你想在代码段之间换行 - 比如你在geom_point和geom_line之间有一个额外的换行符 - 即使使用tidy = FALSE,该换行也会消失. (2认同)