Search code examples
rsweave

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


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.


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