Rev 89901 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
% File src/library/utils/vignettes/Sweave.Rnw% Part of the R package, https://www.R-project.org% Copyright 2002-2026 Friedrich Leisch and the R Core Team% Distributed under GPL 2 or later\documentclass[a4paper]{article}%\VignetteIndexEntry{Sweave User Manual}%\VignettePackage{utils}%\VignetteDepends{tools, datasets, stats, graphics}\title{Sweave User Manual}\author{Friedrich Leisch, Vincent Goulet and R Core Team}\usepackage[round]{natbib}\usepackage{graphicx, Rd}\usepackage{listings}%% colors inspired by classicthesis.sty\usepackage{color}\definecolor{link}{rgb}{0,0.4,0.6} % liens internes\definecolor{url}{rgb}{0.6,0,0} % liens externes\definecolor{citation}{rgb}{0,0.5,0} % citations\definecolor{delim}{rgb}{0.0,0.5,0.5}%% display noweb markers in color in listings; 'literate' key used to%% leave references to chunk 'boxp' alone\lstset{language=[LaTeX]TeX,basicstyle=\small\ttfamily,commentstyle=\slshape,keywordstyle=\mdseries,moredelim=*[s][\color{delim}]{<<}{>>=},moredelim=[l][\color{delim}]{@},literate={<<boxp>>}{<<boxp>>}8,frame=trbl,}\usepackage{hyperref}\hypersetup{%colorlinks,%plainpages=true,%linkcolor=link,%citecolor=citation,%urlcolor=url,%% pdfstartview=FitH,% or Fitpdfstartview={XYZ null null 1},%pdfview={XYZ null null null},%pdfpagemode=UseNone,% for no outlinepdfauthor={Friedrich Leisch and R Core Team},%pdftitle={Sweave User Manual},%pdfsubject={R vignette documentation system}%}\def\subsectionautorefname{Section}\newcommand{\I}[1]{#1}\sloppy\begin{document}\maketitle\section{Introduction}\label{sec:intro}Sweave provides a flexible framework for mixing text and \R{} code forautomatic document generation. A single source file contains bothdocumentation text and \R{} code. The file may then either be\emph{woven} into a final document containing the documentation texttogether with the \R{} code and its output (text, graphs), or\emph{tangled} to extract the \R{} code to a script.This literate programming system \citep{fla:Knuth:1984} allows there-generation of a report if the input data change while alsodocumenting the code to reproduce the analysis in the same file thatcontains the report. The \R{} code of the complete analysis isembedded into a \LaTeX{} document\footnote{\url{https://www.ctan.org}}using the \code{noweb} syntax \citep{flm:Ramsey:1998}. Hence, the fullpower of \LaTeX{} (for high-quality typesetting) and \R{} (for dataanalysis) can be used simultaneously. See\cite{e1071-papers:Leisch:2002} and references therein for moregeneral thoughts on dynamic report generation and pointers to othersystems.Sweave uses a modular concept using different drivers for the actualtranslations. Obviously different drivers are needed for differenttext markup languages (\LaTeX{}, HTML, \ldots). Several packages onCRAN provide support for other word processing systems (see\autoref{sec:faq}).\section{\I{Noweb} files}\label{sec:noweb}\code{noweb} \citep{flm:Ramsey:1998} is a simpleliterate-programming tool which allows combining program source codeand the corresponding documentation into a single file. A\code{noweb} file is a simple text file which consists of a sequenceof code and documentation segments, called \emph{chunks}:\begin{description}\item[Documentation chunks] start with a line that has an at sign(\verb|@|) as first character, followed by a space or newlinecharacter. The rest of this line is a comment and ignored.Typically documentation chunks will contain text in a markuplanguage like \LaTeX{}. The chunk continues until a new code ordocumentation chunk is started: note that Sweave does not interpretthe contents of documentation chunks, and so will identify chunkindicators even inside \LaTeX{} verbatim environments.\item[Code chunks] start with \verb|<<|\code{\var{options}}\verb|>>=| at the beginning ofa line; again the rest of the line is a comment and ignored.\end{description}The default for the first chunk is documentation.In the simplest usage of \command{noweb}, the options (if present) ofthe code chunks give the names of source code files, and the tool\command{notangle} can be used to extract the code chunks from the\code{noweb} file. Multiple code chunks can have the same name, thecorresponding code chunks are then concatenated when the source code isextracted. \command{noweb} has some additional mechanisms tocross-reference code chunks (the \verb|[[...]]| operator, etc.),Sweave does currently not use nor support these features, so they arenot described here.\section{Sweave files}\label{sec:sweavefile}Sweave source files are \code{noweb} files with some additionalsyntax that allows some additional control over the finaloutput. Traditional \code{noweb} files have the extension\file{.nw}, which is also fine for Sweave files (and fully supportedby the software). Additionally, Sweave currently recognizes files withextensions \file{.rnw}, \file{.Rnw}, \file{.snw} and\file{.Snw} to directly indicate a \code{noweb} file with Sweaveextensions. We will use \file{.Rnw} throughout this document.\subsection{A simple example}A minimal Sweave file is shown in \autoref{fig:ex1.Rnw}. The filecontains three code chunks embedded in a simple \LaTeX{}document. Running the following expressions creates the \LaTeX{}document shown in \autoref{fig:ex1.tex}.<<>>=rnwfile <- system.file("Sweave", "example-1.Rnw", package = "utils")Sweave(rnwfile)@<<echo=FALSE>>=rnwfileb <- basename(rnwfile)texfileb <- sub("Rnw$", "tex", rnwfileb)pdffileb <- sub("Rnw$", "pdf", rnwfileb)plotfileb <- sub("\\.tex$", "-003.pdf", texfileb)@Compiling this \LaTeX{} document results in the PDF in\autoref{fig:ex1.pdf}. The latter can also be created directly fromwithin \R{} using<<>>=tools::texi2pdf("example-1.tex")@\begin{figure}[htbp]\centering\begin{minipage}{0.9\textwidth}\lstinputlisting{\Sexpr{rnwfile}}\end{minipage}\caption{A minimal Sweave file: \file{\Sexpr{rnwfileb}}.}\label{fig:ex1.Rnw}\end{figure}\begin{figure}[htbp]\centering\begin{minipage}{0.9\textwidth}\lstinputlisting{\Sexpr{texfileb}}\end{minipage}\caption{Running \code{Sweave("\Sexpr{rnwfileb}")} produces the file\file{\Sexpr{texfileb}}.}\label{fig:ex1.tex}\end{figure}\begin{figure}[htbp]\centering\fbox{\begin{minipage}{0.8\textwidth}\includegraphics[width=\textwidth]{\Sexpr{pdffileb}}\end{minipage}}\caption{The final document \file{\Sexpr{pdffileb}} created bycompiling \file{\Sexpr{texfileb}}.}\label{fig:ex1.pdf}\end{figure}The first difference between \file{\Sexpr{rnwfileb}} and\file{\Sexpr{texfileb}} is that the \LaTeX{} style file\file{Sweave.sty} is automatically loaded, which provides environmentsfor typesetting \R{} input and output (the \LaTeX{} environments\code{Sinput} and \code{Soutput}). Otherwise, the documentation chunksare copied without any modification from\file{\Sexpr{rnwfileb}} to \file{\Sexpr{texfileb}}.The real work of Sweave is done on the code chunks: The first codechunk has no name, hence the default behavior of Sweave is used, whichtransfers both the \R{} commands and their respective output to the\LaTeX{} file, embedded in \code{Sinput} and \code{Soutput}environments, respectively.The second and third code chunks show one of the Sweave extensions to the\code{noweb} syntax: code chunk names can be used to pass options toSweave which control the final output.\begin{itemize}\item The option \code{eval=FALSE} for the second chunk indicates thatthe code should not be evaluated (yet). The code is reused in the thirdchunk (details follow in \autoref{sec:chunkrefs}).\item The third chunk is marked as a figure chunk (\code{fig=TRUE})such that Sweave creates (by default) a PDF file of the plot createdby the commands in the chunk. Furthermore, the statement\verb|\includegraphics{\Sexpr{sub(".pdf", "", plotfileb, fixed=TRUE)}}|is inserted into the \LaTeX{} file (details on the choice of filenames for figures follow later in this manual).\item Option \code{echo=FALSE} indicates that the \R{} input should notbe included in the final document (no \code{Sinput} environment).\end{itemize}\subsection{Sweave options}Options control how code chunks and their output (text, figures) aretransferred from the \file{.Rnw} file to the \file{.tex} file. Alloptions have the form \code{\var{key}=\var{value}}, where \code{\var{value}} can bea number, string or logical value. Several options can be specified atonce (separated by commas), all options must take a value (which mustnot contain a comma or equal sign). Logical options can take thevalues \code{TRUE}, \code{FALSE}, \code{T}, \code{F} as wellas lower-case and capitalized versions of the first two.In the \file{.Rnw} file options can be specified either\begin{enumerate}\item inside the angle brackets at the beginning of a code chunk,modifying the behaviour \emph{only for this chunk}, or\item anywhere in a documentation chunk using the command %\begin{quote}\verb|\SweaveOpts{|\code{\var{opt1}=\var{value1}, \var{opt2}=\var{value2}, ..., \var{optN}=\var{valueN}}\verb|}|\end{quote}which modifies the defaults for the rest of the document, i.e.,\emph{all code chunks after the statement}. Hence, an\verb|\SweaveOpts| statement in the preamble of the document setsdefaults for all code chunks.\end{enumerate}Further, global options can be specified (as a comma-separated list of\code{\var{key}=\var{value}} items) in the call to the function\code{Sweave}, via the \option{--options=} flag of \command{R CMDSweave}, and in the environment variable \env{SWEAVE\_OPTIONS}.Which options are supported depends on the driver in use. All driversshould at least support the following options (all options appeartogether with their default value, if any):\begin{description}\item[\code{split=FALSE}] a logical value. If \code{TRUE}, then the output isdistributed over several files, if \code{FALSE} all output iswritten to a single file. Details depend on the driver.\item[\code{label}] a text label for the code chunk, which is usedfor file-name creation when \code{split=TRUE}. It is also used inthe comments added above the chunk when the file is processed by\command{Rtangle} (provided the \code{annotate} option is true, asit is by default), and as part of the file names for filesgenerated by figure chunks. Because labels can be part of filenames, they should contain only alphanumeric characters and\code{\#+-\_}. (Including the period \code{.} can causeconfusion with file extensions.)\end{description}The first (and only the first) option in a code chunk name can beoptionally without a name, then it is taken to be a label. Therefore,starting a code chunk with\begin{quote}\verb|<<hello, split=FALSE>>|\end{quote}is the same as\begin{quote}\verb|<<split=FALSE, label=hello>>|\end{quote}but\begin{quote}\verb|<<split=FALSE, hello>>|\end{quote}gives a syntax error. Having an unnamed first argument for labels isneeded for \code{noweb} compatibility. If only %\code{{\textbackslash}SweaveOpts} % <- protect from Sweave catching \SweaveOptsis used for setting options, then Sweave files can be written to befully compatible with \code{noweb} (as only file names appear in codechunk names).Note that \code{split=TRUE} should \emph{not} be used in packagevignettes.The help pages for \code{RweaveLatex} and \code{Rtangle} list theoptions supported by the default \code{Sweave} and \code{Stangle} drivers.Now for the promised details on the file names corresponding tofigures. These are of the form \code{\var{prefix}-\var{label}.\var{ext}}.\begin{itemize}\item \code{\var{prefix}} can be set by the option\code{prefix.string}, otherwise is the basename of the output file(which unless specified otherwise is the basename of the inputfile).\item \code{\var{label}} is the label of the code chunk if it hasone, otherwise the number of the code chunk in the range\texttt{001} to \texttt{999}.\item \code{\var{ext}} is the appropriate extension for the type ofgraphics, e.g.{} \code{pdf}, \code{eps}, \ldots{}.\end{itemize}So for the \file{\Sexpr{rnwfileb}} file, the PDF version of theboxplot is \file{\Sexpr{plotfileb}}, since it is the third code chunkin the document. Note that if \code{prefix.string} is used it canspecify a directory as part of the prefix. For example, using\verb|\SweaveOpts{prefix.string=figures/fig}| will result in theauto-generated figures to be placed in the subdirectory \verb|figures|(the Sweave document should arrange to create this directory beforeuse).\subsection{Using multiple input files}\LaTeX{} files can include others via \verb|\input{}| commands. Thesecan also be used in Sweave files, but the included files will beincluded by \LaTeX{} and are not processed by Sweave. The equivalentif you want the included files to be processed is the\verb|\SweaveInput{}| command.Included files should use the same Sweave syntax (see below) andencoding as the main file.\subsection{Using scalars in text}There is limited support for using the values of \R{} objects in textchunks. Any occurrence of\verb|\Sexpr|\verb|{|\code{\var{expr}}\verb|}| is replaced by thestring resulting from coercing the value of the expression \code{expr}to a character vector; only the first element of which being used.For example, \verb|\Sexpr{sqrt(9)}| will be replaced by the string\code{3} in the \LaTeX{} document.The expression in \verb|\Sexpr| is evaluated in the same environmentas the code chunks. Therefore, one can access all objects defined in thecode chunks which have appeared before the expression and wereevaluated. The expression may contain any valid \R{} code, only braces(\verb|{ }|) are not allowed. (This is not really a limitation becausemore complicated computations can be easily done in a hidden codechunk and the result then be used inside \verb|\Sexpr|.)\subsection{Code chunk reuse}\label{sec:chunkrefs}Named code chunks can be reused in other code chunks following laterin the document. Consider the simple example\begin{quote}% NB: this is indented to avoid interpretation by Sweave.\begin{verbatim}<<a>>=x <- 10@<<b>>=x + y@<<c>>=<<a>>y <- 20<<b>>@\end{verbatim}\end{quote}which is equivalent to defining the last code chunk as\begin{quote}\begin{verbatim}<<c>>=x <- 10y <- 20x + y@\end{verbatim}\end{quote}The chunk reference operator \verb|<<>>| takes only the name of thechunk as its argument: no additional Sweave options are allowed.It has to occur at the beginning of a line.References to unknown chunk names are omitted, with a warning.\subsection{Syntax definition}So far we have only talked about Sweave files using \code{noweb} syntax(which is the default). However, Sweave allows the user to redefinethe syntax marking documentation and code chunks, using scalars intext or reuse code chunks.\autoref{fig:ex1.Stex} shows the example from \autoref{fig:ex1.Rnw}using the \code{SweaveSyntaxLatex} definition. It can be created using<<results=hide>>=SweaveSyntConv(rnwfile, SweaveSyntaxLatex)@\begin{figure}[htbp]\centering\begin{minipage}{0.9\textwidth}\lstinputlisting{\Sexpr{sub("Rnw$", "Stex", rnwfileb)}}\end{minipage}\caption{An Sweave file using \LaTeX{} syntax:\file{\Sexpr{sub("Rnw$", "Stex", rnwfileb)}}.}\label{fig:ex1.Stex}\end{figure}Code chunks are now enclosed in \code{Scode}environments, code chunk reuse is performed using\verb|\Scoderef{|\code{\var{chunkname}}\verb|}|. All other operators are the same as inthe \code{noweb}-style syntax.Which syntax is used for a document is determined by the extension ofthe input file, files with extension\footnote{%The lowercase versions are also supported for convenience oncase-insensitive file systems.} %\file{.Rtex} or \file{.Stex} are assumed to follow the \LaTeX-stylesyntax. Alternatively the syntax can be changed at any point withinthe document using the commands\begin{quote}\verb|\SweaveSyntax{SweaveSyntaxLatex}|\end{quote}or\begin{quote}\verb|\SweaveSyntax{SweaveSyntaxNoweb}|\end{quote}at the beginning of a line within a documentation chunk. Syntaxdefinitions are simply lists of regular expression for several Sweavecommands: see the two default definitions mentioned above forexamples.\subsection{Encoding}\LaTeX{} documents written in most languages other than Englishusually require a special input encoding to support accentedcharacters and various symbols beyond those of ASCII. The modern wayto deal with this situation is to use the UTF-8 input encoding andcompile with Lua\LaTeX{}.As from \R{} 3.1.0, the UTF-8 encoding is handled preferentially toother encodings. Sweave will leave UTF-8 code in that encoding, andoutput in that encoding as well. However, it remains required to tellSweave that a file uses this encoding. This can be done througheither the argument \code{encoding} of the function \code{Sweave} orthe flag \option{--encoding} of \command{R CMD Sweave}, or byinserting the comment\begin{quote}\verb|%\SweaveUTF8|\end{quote}in the file to process.If you are still using pdf\LaTeX{} with non-ASCII documents, youshould be using the \LaTeX{} package \pkg{inputenc}, with a statementsuch as\begin{quote}\verb|\usepackage[utf8]{inputenc}|\end{quote}in the document's preamble. There is a wide range of input encodingswhich are supported, at least partially, and the more recent \LaTeX{}package \pkg{inputenx} supports more. Other encodings commonlyencountered in Sweave documents are \code{latin1}, \code{latin9} and\code{ansinew} (the CP1252 codepage on Windows). Greatercoverage\footnote{Including Eastern European, Greek and Hebrewletters.} of UTF-8 can be obtained by\begin{quote}\verb|\usepackage[utf8]{inputenx}| \\\verb|\input{ix-utf8enc.dfu}|\end{quote}The previous paragraphs covered the documentation sections, but what ofthe code sections where \LaTeX{} escapes cannot be used? The firstpiece of advice is to use only ASCII code sections as anything elsewill reduce the portability of your document. But \R{} code can beincluded if in the input encoding declared in the preamble.The next complication is inclusions: the final vignette may wellinclude \R{} output, \LaTeX{} or other Sweave files \emph{via}\verb|\input{}| and \verb|\SweaveInput{}| lines, a bibliography andfigures. It is the user's responsibility that the text inclusions arecovered by the declared input encoding. \LaTeX{} allows the inputencoding to be changed by\begin{quote}\verb|\inputencoding{|\code{\var{something}}\verb|}|\end{quote}statements: these may not work well in Sweave processing. Since\LaTeX{} package loading is typically not legal \LaTeX{} code in anincluded file, it is easiest to declare the encoding to Sweave usingthe \verb|%\SweaveUTF8| comment.It is all too easy for B\textsc{ib}\TeX{} to pick up UTF-8-encodedreferences for a Latin-1 document, or \emph{vice versa}.R output is again to a large extent under the user's control. If aLatin-1 Sweave document is processed by \R{} running a Latin-1 locale ora UTF-8 document is processed in a UTF-8 locale, the only problemswhich are likely to arise are from handling data in another encoding,but it may be necessary to declare the document's encoding to coverthe \R{} output which is generated even if the document is itself ASCII.One common problem is the quotes produced by \code{sQuote()} and\code{dQuote()}: these will be in UTF-8 when \R{} is run in a UTF-8locale, and will be in CP1252 when Sweave is run from \command{Rgui.exe}on Windows. Two possible solutions are to suppress fancy quotes by\code{options(useFancyQuotes=FALSE)} or to force UTF-8 by\code{options(useFancyQuotes="UTF-8")}.The encoding of figures is not usually an issue as they are eitherbitmaps or include encoding information: it may be necessary to usethe \code{pdf.encoding} Sweave option to set the \code{pdf()}device up appropriately.\section{Weaving and tangling}The user front-ends of the Sweave system are the two \R{} functions\code{Sweave} and \code{Stangle}, both contained inpackage~\pkg{utils}. \code{Sweave} runs the code chunks through \R{}and replaces them with any combination of their input and output.\code{Stangle} extracts only the code chunks from an \file{.Rnw} fileand writes them out to one or several files. \code{Stangle} is actuallyjust a wrapper function for \code{Sweave}, which uses a tanglinginstead of a weaving driver by default. See<<eval=FALSE>>=help("Sweave")@for more details and arguments of the functions.\subsection{The \texorpdfstring{\code{RweaveLatex}}{RweaveLatex} driver}This driver transforms \file{.Rnw} files with \LaTeX{} documentationchunks and \R{} code chunks to proper \LaTeX{} files (for typesetting bothwith standard \command{latex} or \command{pdflatex}), see<<eval=FALSE>>=help("RweaveLatex")@for details, including the supported options.\subsubsection{Using objects as chunk options}Starting with \R{} 4.6.0, the \code{RweaveLatex} driver allows the\var{value} of logical and numerical chunk options (only) to be thename of an object defined in earlier, evaluated code chunks. This isuseful to pass computed values to options. The Sweave file in\autoref{fig:ex2.Rnw} provides two examples of use. Processing thefile with<<results=hide>>=rnwfile <- system.file("Sweave", "example-2.Rnw", package = "utils")Sweave(rnwfile)tools::texi2pdf("example-2.tex")@<<echo=FALSE>>=rnwfileb <- basename(rnwfile)pdffileb <- sub("Rnw$", "pdf", rnwfileb)@creates the PDF in \autoref{fig:ex2.pdf}. Note that the second codechunk was not evaluated, and how the proportions of the plot differfrom the otherwise same one in \autoref{fig:ex1.pdf}.\begin{figure}[htbp]\centering\begin{minipage}{0.9\textwidth}\lstinputlisting{\Sexpr{rnwfile}}\end{minipage}\caption{Sweave file \file{\Sexpr{rnwfileb}} with options takingtheir values from objects in the second and third code chunks.}\label{fig:ex2.Rnw}\end{figure}\begin{figure}[htbp]\centering\fbox{\begin{minipage}{0.8\textwidth}\includegraphics[width=\textwidth]{\Sexpr{pdffileb}}\end{minipage}}\caption{The final document \file{\Sexpr{pdffileb}} created from\file{\Sexpr{rnwfileb}}.}\label{fig:ex2.pdf}\end{figure}\subsubsection{Unparsable code in code chunks}In traditional Sweave usage, the expressions in code chunks are alwaysparsed on weaving, whether option \code{eval} is \code{TRUE} or\code{FALSE}. Furthermore, code chunks with \code{eval=FALSE} areautomatically and irrevocably commented out on tangling. Theseconventions may prove limiting in uses of literate programming beyondpure statistical analysis. For example, they make impossible toinclude in a code chunk, say for didactic purposes, invalid R codethat should appear uncommented in the tangled script.To ease with this sort of scenario, \R{} 4.6.0 introduced options forthe standard drivers to completely ignore code chunks on weaving,tangling, or both. With the \code{RweaveLatex} driver, chunks usingthe option \code{ignore.on.weave=TRUE} are not parsed on weaving, butremain written out verbatim on tangling. A shorter alias \code{weave}for \code{!ignore.on.weave} is also supported. An option \code{ignore}also sets at once \code{ignore.on.weave} and the equivalent option for\code{Rtangle}.The Sweave file in \autoref{fig:ex3.Rnw} provides examples of use ofthe option \code{ignore.on.weave} (and of \code{Rtangle} optionsthat are covered later in \autoref{sec:weaving:rtangle}).<<results=hide>>=rnwfile <- system.file("Sweave", "example-3.Rnw", package = "utils")Sweave(rnwfile)tools::texi2pdf("example-3.tex")@<<echo=FALSE>>=rnwfileb <- basename(rnwfile)pdffileb <- sub("Rnw$", "pdf", rnwfileb)@Note the ``missing'' code chunks in the PDF output shown in\autoref{fig:ex3.pdf}.\begin{figure}[htbp]\centering\begin{minipage}{0.9\textwidth}\lstinputlisting{\Sexpr{rnwfile}}\end{minipage}\caption{Sweave file \file{\Sexpr{rnwfileb}} with finer control ofweaving and tangling.}\label{fig:ex3.Rnw}\end{figure}\begin{figure}[htbp]\centering\fbox{\begin{minipage}{0.8\textwidth}\includegraphics[width=\textwidth]{\Sexpr{pdffileb}}\end{minipage}}\caption{The final document \file{\Sexpr{pdffileb}} created from\file{\Sexpr{rnwfileb}}.}\label{fig:ex3.pdf}\end{figure}\subsubsection{Writing to separate files}If \code{split} is set to \code{TRUE}, then all text correspondingto code chunks (the \code{Sinput} and \code{Soutput} environments)is written to separate files. The file names are of form\file{prefix.string-label.tex}. If several code chunks have the samelabel, their outputs are concatenated. If a code chunk has no label,then the number of the chunk is used instead. The same naming schemeapplies to figures. You do need to ensure that the file namesgenerated are valid and not so long that there are not regarded as thesame by your OS (some file systems only recognize 13 characters).\subsubsection{\LaTeX{} style file}The driver automatically inserts the statement\verb|\usepackage{Sweave}| as the last line before\verb|\begin{document}| in the final \LaTeX{} file if the statementis not found in the Sweave source file. The style file\file{Sweave.sty} defines the environments \code{Sinput} and\code{Soutput} for typesetting code chunks. If you do not want toinclude the standard style file, perhaps because you have your owndefinitions for \code{Sinput} and \code{Soutput} environments in adifferent place, simply insert a comment like\begin{quote}\verb|% \usepackage{Sweave}|\end{quote}in the \LaTeX{} preamble of to file to prevent automatic insertion ofthe line.\subsubsection{Figure sizes}The style file \file{Sweave.sty} sets the default \LaTeX{} figurewidth (which is independent of the size of the generated EPS or PDFfiles). The current default is 80\% of the current text width as setwith:\begin{quote}\verb|\setkeys{Gin}{width=0.8\textwidth}|\end{quote}If you want to use another width for the figures that areautomatically generated and included by Sweave, simply add a linesimilar to the one above \emph{after} \verb|\begin{document}|. If youwant no default width for figures, load the style manually with theoption \code{nogin} by inserting the statement\begin{quote}\verb|\usepackage[nogin]{Sweave}|\end{quote}in the preamble.Note that a new graphics device is opened for each figure chunk (onewith option \code{fig=TRUE}), hence all graphical parameters of the\code{par()} command must be set in each single figure chunk and areforgotten after the respective chunk (because the device is closedwhen leaving the chunk).One thing that gets easily confused are the width and heightparameters of the \R{} graphics devices and the correspondingarguments to the \LaTeX{} command \verb|\includegraphics|. The Sweaveoptions \code{width} and \code{height} are passed to the \R{} graphicsdevices, and hence affect the default size of the produced EPS and PDFfiles. They do not affect the size of figures in the document, whichis the default mentioned above. If you want to modify the size ofincluded figures, use \verb|\setkeys{Gin}| or explicit\verb|\includegraphics| commands in combination with the Sweave option\code{include=FALSE}.\subsubsection{Prompts and text width}By default the driver gets the prompts used for input linesand continuation lines from \R{}'s \code{options()} settings. To set newprompts use something like<<eval=FALSE>>=options(prompt = "MyR> ", continue = "...")@See \code{help(options)} for details. Similarly the width of theoutput text is controlled by the \R{} option \code{"width"}.\subsubsection{Graphics devices}The default graphics device for figure chunks is\code{pdf()}: the standard options \code{pdf}, \code{eps},\code{png} and \code{jpg} allow one or more of these to beselected for a particular chunk or (via \verb|\SweaveOpts|) for thewhole document. It can be convenient to select PNG for a particularfigure chunk by something like\begin{verbatim}<<figN, fig=TRUE, pdf=FALSE, png=TRUE>>\end{verbatim}pdf\LaTeX{} and Lua\LaTeX{} should then automatically include the\abbr{PNG} file for that chunk.You can define your own graphics devices and select one of them by theoption \code{grdevice}. The value of the option is a function devicedefined in a hidden code chunk. For example, we could make use of the\code{cairo\_pdf} device by using \code{grdevice=my.Swd} with\code{my.Swd} defined as:\begin{verbatim}my.Swd <- function(name, width, height, ...)grDevices::cairo_pdf(filename = paste(name, "pdf", sep = "."),width = width, height = height)\end{verbatim}Specialized custom graphics devices may need a customized way to shutthem down in place of \verb|graphics.off()|: this can be supplied\emph{via} a companion function \verb|my.Swd.off|, which is calledwith no arguments.For a complete example see the file\file{src/library/utils/tests/customgraphics.Rnw} in the \R{} sources.\subsection{The \texorpdfstring{\code{Rtangle}}{Rtangle} driver}\label{sec:weaving:rtangle}The driver \code{Rtangle} can be used to extract \R{} code chunks froma \file{.Rnw} file. Code chunks can either be written to one largefile, or to separate files (one for each code chunk). The options\code{split}, \code{prefix}, and \code{prefix.string} have the samedefaults and interpretation as for the \code{RweaveLatex} driver. See<<eval=FALSE>>=help("Rtangle")@for further details.Note that when using \code{split=TRUE} with labeled code chunks, theresulting script files sorted alphabetically will most likely notpreserve the logical order of the code.As of \R{} 4.6.0, a number of options give users finer control on thetangling process. First, the option \code{chunk.sep} allows to specifythe separator between code chunks when they are collected in a singlefile (two blank lines by default). One may also use\code{chunk.sep=FALSE} to completely omit the separator (between twochunks when used as a chunk option).Second, \code{Rtangle} also gains an option \code{ignore.on.tangle} tocompletely omit a code chunk on tangling, irrespective of the value ofoption \code{eval} (the option \code{drop.evalFALSE=TRUE} only omitsunevaluated chunks). The driver also supports the shorter alias\code{tangle} for \code{!ignore.on.weave}, and the option\code{ignore} to set both \code{ignore.on.weave} and\code{ignore.on.tangle} at once.Finally, \code{Rtangle} now provides an option \code{extension} tospecify the extension, without the leading dot, for the file name of atangled code chunk when splitting is selected. (Using an extensionother than \code{.R} when \code{split=FALSE} does not appear as afeature worth supporting.) If used as \code{extension=TRUE}, thedefault extension (usually \code{R}) is used. If the option is\code{FALSE}, no extension is added to the file name.The option \code{extension} is specially useful with\code{ignore.on.weave=TRUE} of \code{RweaveLatex} to include code ortext that the engine would not be able to parse on weaving, yet thatneeds to be tangled to a file with a specific extension, such as\code{.sh} or \code{.txt}.The Sweave file in \autoref{fig:ex3.Rnw} takes advantage of the\code{Rtangle} options above. Tangling the file with<<>>=Stangle(rnwfile, split = TRUE, annotate = FALSE, chunk.sep = "\n")@<<echo=FALSE>>=rfile <- sub("\\.Rnw$", "-main.R", rnwfileb)@creates the files in \autoref{fig:ex3.R}.\begin{figure}[htbp]\centering\begin{minipage}{0.9\textwidth}\lstinputlisting[title=\file{\Sexpr{rfile}}]{\Sexpr{rfile}}\end{minipage}\begin{minipage}{0.9\textwidth}\lstinputlisting[title=\file{hello.sh}]{hello.sh}\end{minipage}\begin{minipage}{0.9\textwidth}\lstinputlisting[title=\file{README}]{README}\end{minipage}\caption{Files created by tangling \file{\Sexpr{rnwfileb}}.}\label{fig:ex3.R}\end{figure}\section{Obtaining the name of the processed file}So far, we presented weaving and tangling as separate, somewhatorthogonal procedures. However, one may devise various schemes whereboth weaving \emph{and} tangling are needed to create a document. Hereare a few examples:\begin{itemize}\item maintaining documentation and code together even though the codeis not directly used to create the text;\item code that needs to be included verbatim in a document, but notnecessarily as or where it appears in the sources;\item pieces of code that rely on other pieces being saved as files.\end{itemize}This manual is an example of the third item: the \file{.tex} and PDFfiles in the figures need to be created from the \file{.Rnw} filesbefore they can be included in this document.A nice trick to achieve this consists of embedding a tanglingprocedure \emph{inside} a weaving procedure by calling \code{Stangle}in a code chunk. Now, this requires the name of the file toprocess\ldots{} which is the file being processed. To avoid hardcoding the file name in the \code{Stangle} call, package~\pkg{utils}provides, since \R{} 4.6.0, a function \code{SweaveGetSourceName} thatreturns the name of the file being woven by an \code{Sweave} processlaunched from the command line. This allows to start \texttt{Stangle}inside \texttt{Sweave} with something like:\begin{quote}% NB: this is indented to avoid interpretation by Sweave.\begin{verbatim}<<echo=FALSE, results=hide>>=FILE <- SweaveGetSourceName()Stangle(FILE)@\end{verbatim}\end{quote}The function supports weaving processes started by means of either\command{R~CMD~Sweave}, \command{R~-e}, or \command{Rscript~-e} (see\autoref{sec:faq}).\section{Adding Sweave Drivers}Adding drivers is relatively simple by modelling them on the existing\code{RweaveLatex} and \code{Rtangle} drivers.\footnote{%If you copy the standard drivers, \textbf{do} be careful not toinfringe R-core's copyright: the copyright notices in the \R{}sources \textbf{must} also be copied.}An Sweave driver is a function of no arguments which should return anamed list of five functions:\begin{description}\item{\code{setup(file, syntax, \dots)}} Set up the driver, e.g.{}open the output file. Its return value is an object which is passedto the next three functions, and can be updated by the next two. Thevalue should be a list, and contain a component \code{options}, anamed list of the default settings for the options needed by\code{runcode}.\item{\code{runcode(object, chunk, options)}} Process a code chunk.Returns a possibly updated \code{object}. Argument \code{chunk} is acharacter vector, and \code{options} is a options list for thischunk.\item{\code{writedoc(object, chunk)}} Write out a documentationchunk. Returns a possibly updated \code{object}.\item{\code{finish(object, error)}} Finish up, or clean up if\code{error} is true.\item{\code{checkopts(options)}} Convert or validate \code{options}given as a named list of character strings.\end{description}Note that the \code{setup} function should have a \code{\dots}argument. It will be passed additional arguments from a\code{Sweave()} call, but in future \code{Sweave} may itself setoptions and pass them on the setup function: one such may be theencoding used for the text to be processed.\bibliographystyle{jss}\bibliography{Sweave}\newpage\appendix\section{Frequently Asked Questions}\label{sec:faq}\subsection{How can I get Emacs to automatically recognize filesin Sweave format?}\abbr{ESS}\footnote{\url{https://ESS.R-project.org/}} automaticallyrecognize files with extension \file{.Rnw} as Sweave files and turnon the correct modes. Please follow the instructions on the\abbr{ESS} homepage on how to install \abbr{ESS} on your computer.\subsection{Can I run Sweave directly from a shell?}You may run Sweave and Stangle directly from a shell, rather thanmanually starting \R{} and then running calling \code{Sweave} or\code{Stangle}, using \command{R~CMD~Sweave} and\command{R~CMD~Stangle} (these commands take the name of the file toprocess in argument). For \code{Sweave} and \code{Stangle} callsrequiring many arguments, it may be simpler to pass the call to \R{}by means of \command{R~-e} or \command{Rscript~-e}.\subsection{Why does \LaTeX{} not find my EPS and PDF graphic files whenthe file name contains a dot?}Sweave uses the standard \LaTeX{} package \pkg{graphicx} to handlegraphic files, which automatically chooses the type of file,provided the basename given in \verb|\includegraphics| has noextension. Hence, you may run into trouble with graphics handlingif the basename of your Sweave file contains dots: \file{foo.Rnw}is OK, while \file{foo.bar.Rnw} is not.\subsection{Empty figure chunks give \LaTeX{} errors.}When a code chunk with \code{fig=TRUE} does not call any plottingfunctions, invalid PDF (or EPS) files may be created. Sweave cannotknow if the code in a figure chunk actually plotted something ornot, so it will try to include the graphics, which is bound tofail.\subsection{Why do R lattice graphics not work?}In recent versions of Sweave they do if they would when run at thecommand line: some calls (e.g.{} those inside loops) need to beexplicitly \code{print()}-ed.\subsection{How can I get Black \& White lattice graphics?}What is the most elegant way to specify that strip panels are to havetransparent backgrounds and graphs are to be in black and white whenlattice is being used with Sweave? I would prefer a global option thatstays in effect for multiple plots.Answer by \I{Deepayan Sarkar}: I'd do something like this as part ofthe initialization:\begin{verbatim}<<...>>=library(lattice)ltheme <- canonical.theme(color = FALSE) ## in-built B&W themeltheme$strip.background$col <- "transparent" ## change strip bglattice.options(default.theme = ltheme) ## set as default@\end{verbatim}\subsection{Creating several figures from one figure chunk doesnot work}Consider that you want to create several graphs in a loop similarto\begin{verbatim}<<fig=TRUE>>=for (i in 1:4) plot(rnorm(100)+i)@\end{verbatim}This will currently \emph{not} work, because Sweave allows\emph{only one graph} per figure chunk. The simple reason is thatSweave opens a device before executing the code and closes itafterwards. If you need to plot in a loop, you have to program italong the lines of\begin{verbatim}<<results=tex, echo=FALSE>>=for(i in 1:4) {fname <- paste("myfile", i, ".pdf", sep = "")pdf(file = fname, width = 6, height = 6)plot(rnorm(100)+i)dev.off()cat("\\includegraphics{", fname, "}\n\n", sep = "")}@\end{verbatim}\subsection{How can I set default\texorpdfstring{\code{par()}}{par()} settings for figure chunks?}Because Sweave opens a new device for each graphics file in eachfigure chunk, using \code{par()} has only an effect if it is usedinside a figure chunk. If you want to use the same settings for aseries of figures, it is easier to use a hook function thanrepeating the same \code{par()} statement in each figure chunk.The effect of\begin{verbatim}options(SweaveHooks = list(fig = function() par(bg = "red", fg = "blue")))\end{verbatim}should be easy to spot.\subsection{How can I change the formatting of R input and outputchunks?}Sweave uses the \pkg{fancyvrb} package for formatting all \R{} codeand text output. \pkg{fancyvrb} is a very powerful and flexiblepackage that allows fine control for displaying text in verbatimenvironments. If you want to change the default layout, simply readthe \pkg{fancyvrb} documentation and modify the definitions ofthe \code{Sinput} and \code{Soutput} environments in\file{Sweave.sty}, respectively.\subsection{How can I change the line length of R input andoutput?}Sweave respects the desired line length of R, namely\code{options("width")}. Therefore, after e.g.\ \code{options(width= 40)} lines will be formatted to have at most 40 characters (ifpossible).\subsection{Can I use Sweave for Word files?}Not directly, but package~\CRANpkg{officer} providesfunctionality to manipulate Microsoft Word documents from R.\subsection{Can I use Sweave for \I{OpenDocument} files?}Not directly. Package \CRANpkg{odfWeave} (archived in 2018) provided functions for using Sweave incombination with OpenOffice Writer rather than \LaTeX.See the \href{https://CRAN.R-project.org/view=ReproducibleResearch}{CRANTask View: Reproducible Research} for an up-to-date list of relateddevelopments.\subsection{Can I use Sweave for HTML files?}Yes, package \CRANpkg{R2HTML} provides a driver for using Sweave incombination with HTML rather than \LaTeX.\subsection{After loading package \pkg{R2HTML} Sweave doesn'twork properly!}Package \CRANpkg{R2HTML} registers an Sweave driver for HTML filesusing the same file extensions as the default \code{noweb}syntax, and after that its syntax is on the search list before thedefault syntax. Using\begin{verbatim}options(SweaveSyntax = "SweaveSyntaxNoweb")\end{verbatim}or calling Sweave like\begin{verbatim}Sweave(..., syntax = "SweaveSyntaxNoweb")\end{verbatim}ensures the default syntax even after loading package \CRANpkg{R2HTML}.\end{document}%%% Local Variables:%%% mode: latex%%% TeX-master: t%%% End: