Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Sweave code chunks inside some framed box?

Tags:

r

latex

tex

sweave

I would like to make an R code chunk (in Sweave) printed inside a framed box in the resulting pdf.

Is there an easy solution for doing that?

like image 996
Tal Galili Avatar asked Jan 18 '23 18:01

Tal Galili


1 Answers

The short answer is that yes, there is an easy way. Just add the following lines, or something like them to the preamble of your Sweave document:

\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
                                              frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
                                              frame=single}

This works because the appearance of code (and output) chunks is controlled by the definition of the Sinput and Soutput environments. These are both Verbatim environments as provided by the LaTeX package fancyvrb. (Click here for a 73 page pdf describing the numerous options that fancyvrb provides).

A quick look in the file Sweave.sty reveals the default definition of those two environments:

\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl}

To change those definitions, just add \DefineVerbatimEnvironment statements of your own devising either: (a) at the end of the Sweave.sty file; or (b) at the start of your *.Snw document.


Finally, here's an example to show what this looks like in practice:

\documentclass[a4paper]{article}

\usepackage{Sweave}

\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
                                              frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
                                              frame=single}
\title{Sweave with boxes}

\begin{document}
\maketitle

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

Here is an example of a code chunk followed by an output chunk,
both enclosed in boxes.

<<>>=
print(rnorm(99))
@

\end{document}

enter image description here

like image 136
Josh O'Brien Avatar answered Jan 28 '23 02:01

Josh O'Brien