\documentclass{article}
\usepackage{url}
\usepackage{natbib}
\usepackage{float}
% \usepackage{exercises}
\usepackage{nextpage}
\setcounter{tocdepth}{1}
\setlength{\voffset}{-3.5cm}
\setlength{\hoffset}{-2cm} \setlength{\textwidth}{15.5cm}
\setlength{\textheight}{24.75cm}
\title{Document that Demonstrates Various Sweave Features}
\author{Lecturer: John Maindonald}
\begin{document}

\section*{Sweave markup}

To ensure that comments are reatined in your code, place the
following in your document preamble (actually it does not have to be
in the preamble).
\begin{verbatim}
\\SweaveOpts{keep.source=TRUE}
\end{verbatim}

\paragraph{Setup at the beginning}

\begin{verbatim}
<<setup, echo=F>>=
opt <- options(SweaveHooks=list(fig=function(){par(cex=0.8,
                         mar=c(4.1,3.6,1.6,1.1), pty="s", lwd=1,
                         mgp=c(2.25,0.5,0), tck=-0.025)}))
pdf.options(pointsize=8)
@%
\end{verbatim}
You can also have \texttt{options(prompt="  ", continue="    ")},
or \texttt{options(continue="    ")}
If you want the first od these options, use it once everything is working.  
Also, include near the end of your document:
\begin{verbatim}
<<prompt, eval=t, echo=f>>=
options(prompt="> ", continue="+  ")
## 
@ %
\end{verbatim}
If your document does not process properly through Sweave, and
you have turned off the prompt and continuation prompt, you can 
restore it by typing at the command line:
\begin{verbatim}
options(prompt="> ", continue="+  ")
\end{verbatim}

\subsection*{Create named code fragment, use, execute}
For example
\begin{verbatim}
%% Create named code fragment
<<countzeros, eval=f, echo=f>>=
countzeros <- function(x)sum(!is.na(x) & x==0)
aggregate(allsets[, c("re74", "re75", "re78")], list(group=allsets$trt), 
          FUN=countzeros)
@ %

%% Execute code fragment, do not echo
<<do-countzeros, echo=f, eval=t>>=
<<countzeros>>
@ %

%% Echo code
<<code-countzeros, echo=t, eval=f>>=
<<countzeros>>
@ %
\end{verbatim}
Use the argument \texttt{results=hide}, if you wish to hide
any results from the calculation.

\subsection*{Graphs}

Here is an example
\begin{verbatim}
%% Create named code fragment (here called 'hist')
<<hist, echo=f, eval=f>>=
library(lattice)
print(histogram(~educ | trt, data=allsets, layout=c(4,1)))
@ %

%% Create graph
\setkeys{Gin}{width=\linewidth}
\begin{figure}
<<do-hist, fig=t, width=8, height=3.75, echo=f>>=
<<hist>>
@ % 
\caption{Histograms, used to compare distributions of Years of education.}    
\end{figure}
\end{verbatim}
Note that \verb!@ %! in place of \verb!@! is optional.  The \verb!%!
tells editors to respect the line feed when reformatting.

\end{document}