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}
If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it. Note that both methods use the same mechanism; RStudio's “Knit” button calls rmarkdown::render() under the hood.
Formatting Text To write text in bold font, use a double asterix or underscores before and after the text.
To make the formatted text into bold type, you can simply use a pair of ** around the marked up text with no space. For example **bold** in the . Rmd file generates bold in the output document.
You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With