20

我正在使用带有 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))

任何解决此问题的帮助将不胜感激!

4

2 回答 2

22

尝试块选项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))
```
于 2012-07-03T08:15:32.173 回答
2

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

示例:将下面的原始文本复制到 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 )
于 2014-08-19T21:05:43.300 回答