I have a very simple sweave chunk with two lines, like this:


How can I center this element? I've tried embracing the chunk with \begin{center} to no avail.


A verbatim environment by default has the width equal to the text width. Thus you cannot center it: the trailing whitespace is included in the line.

Fortunately, Sweave.sty uses fancyvrb package internally. Sweave defines three environments, for the input, output and code, using fancyvrb in the following way:


Now fancyvrb has several environments. One which is helpful in your case is BVerbatim: the text is put into a box with the width by default equal to the width of the longest line of the text. The resulting box can be centered.

Thus the following works:

\noindent\rule{\textwidth}{.1pt} % To show centering

We redefined Soutput as BVerbatim, and the output is now centered:

enter image description here

Note that only the output is centered in this example. To center input, redefine Sinput as well.

  • Really nice answer! – Alan Munn Aug 2 '13 at 21:42
  • @Boris, I've just noticed one problem with that configuration. At the end of the file, I insert another verbatim chunk which is just a print of part of a data frame. However, \DefineVerbatimEnvironment{Soutput}{Verbatim}{} prevents page breaking, so that last chunk will never fit the page (it has 129 rows and 3 cols). How can I prevent this? – Waldir Leoncio Aug 6 '13 at 22:43
  • Well, BVerbatim is a box, so it is not splittable. Redefine the Soutput back to Verbatim just before this large chunk. – Boris Aug 7 '13 at 2:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.