How to wrap text in R source with tidy and knitr

knitr, r

Solution

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.")

Problem

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

Original source