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

24
我正在使用R Markdown中的knitr包创建HTML报告。当我使用'+'时,我的代码很难保持在不同的行上。
例如,
```{r}
ggplot2(mydata, aes(x, y)) +
   geom_point()
```

将返回以下HTML文档

ggplot2(mydata, aes(x, y)) + geom_point()

通常情况下这是没问题的,但当我开始添加额外的行时,问题就出现了,因为我想把它们分开以使代码更易于理解。运行以下代码:

```{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))
```
会导致所有代码都在一行内显示,使其更难以跟踪:
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))
任何帮助解决这个问题都将不胜感激!
2个回答

27

尝试使用 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))
```

有没有一种方法可以全局设置整个文档? - wch
5
是的,我记得 opts_chunk$set(tidy = FALSE) 的意思是关闭代码块的自动整理功能。 - kohske
2
嗯。如果你想在代码的不同部分之间插入换行符——比如在geom_point和geom_line之间多加了一个换行符——即使设置tidy=FALSE,该换行符也会消失。 - jebyrnes

2

我找到的一种将代码块的“整洁”设置更改为false的方法是添加中间命令注释。这似乎使整个代码块被处理为非整洁的,从而尊重您在代码中拥有(或没有)的换行符。不幸的是,这并没有在特定位置(对于特定行)添加换行符。

示例:将下面的原始文本复制到Rmd文件中,并使用knitr进行处理。

整理(即默认值)

输入

```{r eval=FALSE}
# Line comments do not seem to change tidiness.
list(
    sublist=list( 
        suba=10, subb=20 ),
    a=1,
    b=2 ) # End of line comment does not seem to change tidiness.
    
list(
    sublist=list( 
        suba=10, subb=20 ),
    a=1,
    b=2 )

```

输出

# Line comments do not seem to change tidiness.
list(sublist = list(suba = 10, subb = 20), a = 1, b = 2) # End of line comment does not seem to change tidiness.

list(sublist = list(suba = 10, subb = 20), a = 1, b = 2)

未整理

输入

```{r eval=FALSE}
list(
    sublist=list( 
        suba=10, subb=20 ),
    a=1, # Mid-command comment seems to "untidy" the chunk.
    b=2 )
    
list(
    sublist=list( 
        suba=10, subb=20 ),
    a=1,
    b=2 )

```

输出

list(
    sublist=list(
        suba=10, subb=20 ),
    a=1, # Mid-command comment seems to "untidy" the chunk.
    b=2 )

list(
    sublist=list(
        suba=10, subb=20 ),
    a=1,
    b=2 )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接