How to automatically prevent R inputs in Sweave from running off the right margin?

StackOverflow https://stackoverflow.com/questions/15096594

  •  15-03-2022
  •  | 
  •  

Question

Is it possible to get Sweave to automatically print R inputs over multiple lines ? For example,

\documentclass{article}

\begin{document}
\SweaveOpts{concordance=TRUE}
\setkeys{Gin}{width=\textwidth}

<<fig=TRUE>>=
plot(LakeHuron, ylab="Level in feet", xlab="Year", main="Level of Lake Huron 1875–1972", lwd=2, las=1) 
@

\end{document}

will print the R codes to run into (and beyond) the right hand margin. From what I can deduce,

<<>>=
options(width=60)
@ 

only controls R output.

Was it helpful?

Solution

Using , you can try adding the argument keep.source = FALSE to your code chunk, but this still won't always solve your problem by default (it didn't in this particular example).

Here is a crop of the output of what you currently have with:

<<fig=TRUE>>=
plot(LakeHuron, ylab="Level in feet", xlab="Year", main="Level of Lake Huron 1875–1972", lwd=2, las=1) 
@

enter image description here

Here is a crop of the output if we add keep.source = FALSE

<<fig=TRUE, keep.source=FALSE>>=
plot(LakeHuron, ylab="Level in feet", xlab="Year", main="Level of Lake Huron 1875–1972", lwd=2, las=1) 
@

enter image description here

And, here is a crop of the output if we cheat a little bit and reorder the arguments manually. Notice I've placed the problematic title as the last item:

<<fig=TRUE, keep.source=FALSE>>=
plot(LakeHuron, ylab="Level in feet", xlab="Year", lwd=2, las=1, main="Level of Lake Huron 1875-1972") 
@

enter image description here

OTHER TIPS

I do use knitr to compile .Rnw files, which provides access to some very handy code chunk options (like tidy.opts). Using the code below, I think, might solve your text overflow problem above your figure.

\documentclass{article}

\begin{document}
\setkeys{Gin}{width=\textwidth}

<<fig=TRUE, tidy.opts=list(keep.blank.line=FALSE, width.cutoff=50)>>=
plot(LakeHuron, ylab="Level in feet", xlab="Year", main="Level of Lake Huron 1875–1972", lwd=2, las=1) 
@

\end{document}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top