添加中的R降价换行符到代码块(Adding a line break to code blocks

2019-06-26 00:17发布

我现在用的是knitr包有R降价创建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))

在解决任何帮助,这将不胜感激!

Answer 1:

尝试块选项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))
```


Answer 2:

我发现改变块的假的“整洁”设置的一种方法是增加中间命令评论 。 这似乎使加工非整齐整个块,从而尊重换行符你有(或没有)在你的代码。 不幸的是,这并不加在具体位置的换行符(特定行)。

实施例:下面的原始文本复制到一个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)

Untidied

输入

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


文章来源: Adding a line break to code blocks in R Markdown
标签: r markdown knitr