如何在R Markdown中自动实现文本和代码块之间的不同间距?

时间:2019-06-21 13:03:00

标签: r r-markdown

考虑以下R Markdown文档:

---
title: "Stack Overflow Question"
author: "duckmayr"
date: "6/21/2019"
output: pdf_document
header-includes:
    - \usepackage{setspace}
    - \doublespacing
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Here is some example text.
I want all the body text to be double-spaced,
but I want all echoed code from code chunks to be single spaced.
In other words, not this:

```{r}
## This code is double-spaced.
## I want it to be single spaced.
## How can I do that?
```

enter image description here

是否有一种固定的或相对简单的方法来将所有普通文本都以双倍行距排列,但是否所有代码都从代码块中以单倍行距回显?我尝试咨询块选项here的指南,但找不到我想要的东西。

1 个答案:

答案 0 :(得分:2)

如果要输出为pdf,最轻松的方法可能是在Rmd文档中添加一些LaTeX命令:

---
title: "Stack Overflow Question"
author: "duckmayr"
date: "6/21/2019"
output: pdf_document
header-includes:
    - \usepackage{setspace}
    - \doublespacing
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Here is some example text. I want all the body text to be double-spaced, but I
want all echoed code from code chunks to be single spaced. In other words, not
this:

\singlespacing
```{r}
## This code is double-spaced.
## I want it to be single spaced.
## How can I do that?
```

\doublespacing
Some additional body text. Nor hence hoped her after other known defer his. 
For county now sister engage had season better had waited. Occasional mrs 
interested far expression acceptance. Day either mrs talent pulled men 
rather regret admire but. Life ye sake it shed. Five lady he cold in meet up. 

pdf-output 另外,您可以使用knitr块挂钩定义新的块选项。例如,您可以在设置块中添加:

```{r setup, include=FALSE}
hook_chunk = knitr::knit_hooks$get('chunk')

knitr::knit_hooks$set(chunk = function(x, options) {
  regular_output = hook_chunk(x, options)
  # add latex commands if chunk option singlespacing is TRUE
  if (isTRUE(options$singlespacing)) 
    sprintf("\\singlespacing\n %s \n\\doublespacing", regular_output)
  else
    regular_output
})

knitr::opts_chunk$set(echo = TRUE, singlespacing = TRUE)
```

一些有用的参考文献: