user1398057
user1398057

Reputation: 1159

In R markdown in RStudio, how can I prevent the source code from running off a pdf page?

I currently have some code that looks like so:

```{r, tidy=TRUE}
plot(DT$age, DT$height, xlab = "Age of participant in Trials", ylab = "Height of participant in       Trials")
```

Now, it was my understanding that setting tidy to TRUE would make it so that when I knit the code together, the code would not go running off the page and would wrap by itself. However, I sporadically still get run off source code displays when I do commands like the one above. Is there another function that would guarantee the wrapping of code? Thanks!

Upvotes: 48

Views: 87839

Answers (2)

jng
jng

Reputation: 159

The formatR solution also did not work for me, what worked for me was adding the below code to the YAML metadata

---
title: ...
author: ...
header-includes:
  \usepackage{fvextra}
  \DefineVerbatimEnvironment{Highlighting}{Verbatim}{breaklines,commandchars=\\\{\}}
---

In the .tex file, the Highlighting environment is used to print the code. The code above redefines the default Highlighting environment to include the breaklines option, which requires the fvextra package and creates the line wrap for us.

Upvotes: 15

juba
juba

Reputation: 49033

Use the width.cutoff argument inside tidy.opts knitr options to specify the output width :

```{r, tidy=TRUE, tidy.opts=list(width.cutoff=60)}
plot(DT$age, DT$height, xlab = "Age of participant in Trials", ylab = "Height of participant in trials")
```

You can define this option globally for your whole file with a chunk like this :

```{r}
library(knitr)
opts_chunk$set(tidy.opts=list(width.cutoff=60),tidy=TRUE)
```

The tidy.opts options are passed to the formatR package which does the tidying (if I understand correctly). In-depth informations about formatR can be found here :

http://yihui.name/formatR/

Upvotes: 46

Related Questions