Question

I know I can format all my code manually if I set tidy=FALSE for the relevant code block, but I love the tidy=TRUE option. It makes my code look good! But I have a long vector that I want to print and it is going off the line and causing a LaTeX badbox.

Edit -- I know people like examples. Here's an example.

<<HolySnail>>=
X <- data.frame(p1=c(0,2,0,0,-1,1),
                p2=c(3,0,1,1,0,1),
                p3=c(0,0,3,2,1,1))
poor_formatting_requires_tidying <- function(x,y,z) { a <- x*y+z; return(a+z) }
@

Edit -- the question is "How can I force knitr to respect the linebreaks in the definition of X without setting tidy=FALSE?"

Was it helpful?

Solution

I guess you were just looking for an option to control the width of your source code? Setting the width is very tricky with tidy = TRUE; you often have to try different values to get an appropriate width. You can use the tidy.opts option to pass the width.cutoff argument to formatR::tidy.source(), e.g.

\documentclass{article}
\begin{document}
<<HolySnail, tidy.opts=list(width.cutoff=60)>>=
X <- data.frame(p1=c(0,2,0,0,-1,1),
                p2=c(3,0,1,1,0,1),
                p3=c(0,0,3,2,1,1))
poor_formatting_requires_tidying <- function(x,y,z) { a <- x*y+z; return(a+z) }
@
\end{document}

Note width.cutoff only sets the minimal width, which means the output may well be wider than your setting. It depends on whether R can really break the code after width.cutoff characters.

After you struggle more with tweaking the width value, you probably will just go back to tidy = FALSE...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top