Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I automate different spacing between text and code blocks in R Markdown?

Tags:

r

r-markdown

Consider the following R Markdown document:

---
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

Is there a canned or relatively painless way to have all normal text double-spaced, but have all code echoed from code chunks single spaced? I tried consulting the guide to chunk options here, but couldn't quite find what I was looking for.

like image 590
duckmayr Avatar asked Oct 15 '22 13:10

duckmayr


1 Answers

If you are outputting to pdf the most painless way might be adding some LaTeX commands to your Rmd document:

---
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 Alternatively, you could define a new chunk option using knitr chunk hooks. For instance, you could include in the setup 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)
```

Some useful references:

  • Hooks - Customizable functions to run before/after a code chunk, tweak the output, and manipulate chunk options
  • How to Create New Chunk Options in R Markdown
like image 61
Joris C. Avatar answered Oct 18 '22 22:10

Joris C.