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

duc*_*ayr 5 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?
```
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

是否有一种固定的或相对轻松的方法可以让所有正常文本双倍行距,但所有代码都从代码块中回显单行距?我尝试在此处查阅块选项指南,但无法完全找到我要找的东西。

Jor*_*hau 3

如果您要输出为 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. 
Run Code Online (Sandbox Code Playgroud)

pdf输出 或者,您可以使用knitr chunk hooks 定义一个新的 chunk 选项。例如,您可以在设置块中包含:

```{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)
```
Run Code Online (Sandbox Code Playgroud)

一些有用的参考: