Gregory
Gregory

Reputation: 4279

How to wrap text in R source with tidy and knitr

I'm working with knitr lately and while most aspects of that have gone quite smoothly, there's one formatting issue with including R code in the finished document that I haven't figured out. I often need to create relatively long text strings in my R chunks, e.g. captions for xtable() functions. While tidy generally does a great job at wrapping R code and keeping it in the shaded boxes in LaTeX, it doesn't know what to do with text stings, so it doesn't wrap them, and they flow off the right side of the page.

I would be most happy with a solution that has tidy doing all the work. However, I'd also be satisfied with a solution that I can apply manually to long strings in R chunks in my Rnw source. I just don't want to have to edit the tex file created by KnitR.

Below is a minimal working example.

\documentclass[12pt, english, oneside]{amsart}

\begin{document}

<<setup, include=FALSE, cache=FALSE, tidy=TRUE>>=
options(tidy=TRUE, width=50)
@

<<>>=
x <- c("This","will","wrap","nicely","because","tidy","knows","how","to","deal","with","it.","So","nice","how","it","stays","in","the","box.")
longstr <- "This string will flow off the right side of the page, because tidy doesn't know how to wrap it."
@

\end{document}

Upvotes: 12

Views: 14431

Answers (3)

lawyeR
lawyeR

Reputation: 7664

This answer is a bit late to the party, but I have found that even when I use tidy.opts = list(width.cutoff = 60) in an early chunk (using RStudio and a .Rnw script) and then in each chunk option list I include tidy = TRUE, the overflow of lines still happens. My overflow lines are in sections of code that create ggplot2 plots. Trial and error discovered that if I add a carriage return after the + at the end of a line, I have no overflow problems. The extra line does not show up in the PDF that LaTeX creates.

Upvotes: 1

prabhasp
prabhasp

Reputation: 528

The other solution is to use strwrap.

> longstr <- "This string will flow off the right side of the page, because tidy doesn't know how to wrap it."
> strwrap(longstr, 70)
[1] "This string will flow off the right side of the page, because tidy" "doesn't know how to wrap it."                                      
> str(strwrap(longstr, 70))
chr [1:2] "This string will flow off the right side of the page, because tidy" "doesn't know how to wrap it."

Unfortunately, I do not know whether this will work with tidy, but it works extremely well with knitr's HTML output.

Upvotes: 3

Brian Diggs
Brian Diggs

Reputation: 58835

This is an extremely manual solution, but one which I have used.

You build the string up, using paste0 and that gives tidy a chance to split it.

longstr <- paste0("This string will flow off the right side"," of the page, because tidy doesn't know how to wrap it.")

Upvotes: 4

Related Questions