Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap text in R source with tidy and knitr

Tags:

r

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}
like image 308
Gregory Avatar asked Feb 15 '13 19:02

Gregory


People also ask

How do you use the Knitr in RStudio?

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.

How do you make something bold in R?

Formatting Text To write text in bold font, use a double asterix or underscores before and after the text.

How do you make words bold in R markdown?

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.

How do I add R code to markdown?

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


1 Answers

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.

like image 97
prabhasp Avatar answered Oct 02 '22 17:10

prabhasp