我正在使用带有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))
非常感谢任何解决此问题的帮助!
答案 0 :(得分:18)
尝试chunk选项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))
```
答案 1 :(得分: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 )