\documentclass{article} \title{Sweave Example} \author{Kate Cowles} \usepackage{Sweave} \begin{document} \maketitle The {\tt Sweave} function facilitates creation of documents that blend R code, its output, and documentation or other text. The user begins by creating a {\tt noweb} source file, which is a text file with the extension {\tt.Rnw}. It resembles a {\tt .tex} file, but it has two kinds of segments (called ``chunks") in it: \emph{documentation chunks} and \emph{code chunks}. By default, the document begins with a documentation chunk. Each code chunk must start with \begin{verbatim} <<>>= \end{verbatim} at the beginning of a line. Optionally, a name for the code chunk may be included in the angle brackets: \begin{verbatim} <>= \end{verbatim} Code chunk names may be used to pass options to Sweave to control the final output. Each documentation chunk (except the first) begins with \begin{verbatim} @ \end{verbatim} at the beginning of a line. In this example, we create a small data frame, run a linear regression model, and produce diagnostic plots. Since we do not specify any options in a code chunk name, the default behavior occurs: both the code and its output are included in the final document. <<>>= set.seed(15) x <- 1:5 y <- rnorm(1 -0.5* x ) mydat <- data.frame(cbind(x,y)) print(mydat) summary( lmout <- lm( y ~ x, data=mydat) ) @ Next we will create plots. The options {\tt fig} and {\tt echo} in the code chunk name tell Sweave to include the actual plots produced, and to suppress printing (echoing) of the R code. \begin{center} <>= par(mfrow=c(2,2)) plot(lmout) @ \end{center} This time we will show the code that produces the figure, instead of the figure itself. \begin{center} <>= par(mfrow=c(2,2)) plot(lmout) @ \end{center} It is also possible to include the scalar results of R expressions in text chunks. For example, the logit of 0.237 is \Sexpr{ log( 0.237/( 1-0.237)) }. To process this .Rnw file, one goes into R and runs the Sweave function. \begin{verbatim} Sweave(file="firsttry.Rnw") \end{verbatim} Alternatively, if working in Linux or Unix, one may enter \begin{verbatim} echo 'Sweave("firsttry.Rnw")' | R --vanilla --quiet \end{verbatim} at the Linux/Unix prompt without having to go into R. Either way of running the {\tt Sweave} function will create the \LaTeX\ source file {\tt firsttry.tex} and the graphics files {\tt firsttry-002.pdf} and {\tt firsttry-002.ps}. The final typeset document may be produced by running \begin{verbatim} latex firsttry \end{verbatim} at the Linux/Unix prompt. If in Windows, a batch file or the TeXnic Center may be used to process the {\tt .tex} file. \end{document}