Skip to Content

Using Sweave to Generate Reports from R

Sweave

  • R/S code + LaTex
  • Used for writing R documentation and reports.
  • Syntax is based on NoWeb (http://www.cs.tufts.edu/~nr/noweb/), a tool for literate programming.
  • Sweave file extensions can be the noweb .nw suffix, or one of .rnw, .Rnw, .snw, .Snw

A Sweave file comprises:

Doc chunks : Marked by a line beginning with @. LaTeX markup.
Code chunks : Marked by a line beginning with <<label, opt1=opt1val, opt2=opt2val>>=. R/S code.

In code chunks:

  • label and options are optional
  • If the first key in the options list has no value, it is assumed to be a label
  • All other options must have a value
  • You can also explicitly set the option label=value
  • Labelled code chunks can be reused later in the document, by using the syntax <<label>> inside another code chunk.

Sweave options allow you to modify how the LaTeX document is generated. They can be specified:

  • Globally : Using \SweaveOpts{opt1=opt1val, opt2=opt2val} in the preamble
  • For the Remainder of the Document : Using \SweaveOpts{opt1=opt1val, opt2=opt2val} in the document body
  • For the Current Block : Using <<opt1=opt1val,opt2=opt2val>>=

Scroll down for a full list of options when using the (default) RweaveLatex driver.




Processing Sweave Files

    In the R base package utils:

    Stangle() : extracts code from the sweave file and generates a valid R/S file which can be run using source()

    Sweave() : combines the documentation, code chunks and their output (depending on the specified sweave options) into a single LaTeX document.

    SweaveHooks can be defined as a list of functions associated with a given logical Sweave option. These functions will be called before running any code which has that option set to true. The most common use of this feature is to set graphical parameters for a set of figure chunks

    #assuming we've pre-defined the function graphics.setup
    #to define some graphics parameters
    options(SweaveHooks=list(fig=graphics.setup))
    




    An example

    Sweave File:

    \documentclass[a4paper]{article}
    
    \begin{document}
    
    \title{This is an example}
    \author{I Made This}
    \maketitle
    
    This is an example of using Sweave to do stuff.
    
    <<>>= code chunk. This is an unprocessed comment. By default, code and output will appear in the processed LaTeX file. 
    
    vals<-rnorm(1000)
    length(vals)
    vals[1:10]
    
    
    @ and back to doc chunk. This is an unprocessed comment
    
    And here we can discuss the above code and resulting plot using \LaTeX{} markup
    
    @ we can use \Sexpr{} to do little bits of S calculations in text:
    
    We are using a sample size of \Sexpr{length(vals)} to generate the following plot:
     
    <<fig=T, echo=F>>= opts say: "this is a figure", and "don't output the code"
    
    plot(density(vals))
    
    @
    And we have a density distribution plot in our output
    
    \end{document}
    

    Process the Sweave file in R:

    library(utils)
    Sweave("filename.rnw")
    

    Resulting LaTeX file

    \documentclass[a4paper]{article}
    
    \usepackage{Sweave}
    \begin{document}
    
    \title{This is an example}
    \author{I Made This}
    \maketitle
    
    This is an example of using Sweave to do stuff.
    
    \begin{Schunk}
    \begin{Sinput}
    > vals <- rnorm(x)
    > length(vals)
    \end{Sinput}
    \begin{Soutput}
    [1] 1000
    \end{Soutput}
    \begin{Sinput}
    > vals[1:10]
    \end{Sinput}
    \begin{Soutput}
     [1] -1.43853120 -0.59130624  0.40591950 -0.13001097  1.79179561  0.76275132
     [7] -1.68214854 -1.00586198 -0.04645425  0.15860046
    \end{Soutput}
    \end{Schunk}
    
    And here we can discuss the above code and resulting plot using \LaTeX{} markup
    
    
    We are using a sample size of 1000 to generate the following plot:
    
    
    
    \includegraphics{sweave_test-002}
    
    And we have a density distribution plot in our output
    
    \end{document}
    

    Generate DVI and PDf

    R CMD pdflatex sweave_test.tex
    

    Final PDF File

    generated pdf file





    Valid Options for the R Sweave Driver

    echo
    logical ('TRUE'). Include S code in the output file?
    keep.source
    logical ('FALSE'). When echoing, if 'keep.source ==TRUE' the original source is copied to the file. Otherwise, deparsed source is echoed.
    eval
    logical ('TRUE'). If 'FALSE', the code chunk is not evaluated, and hence no text or graphical output produced.
    results
    character string ('verbatim'). If 'verbatim', the output of S commands is included in the verbatim-like Soutput environment. If 'tex', the output is taken to be already proper latex markup and included as is. If 'hide' then all output is completely suppressed (but the code executed during the weave).
    print
    logical ('FALSE') If 'TRUE', each expression in the code chunk is wrapped into a 'print()' statement before evaluation, such that the values of all expressions become visible.
    term
    logical ('TRUE'). If 'TRUE', visibility of values emulates an interactive R session: values of assignments are not printed, values of single objects are printed. If 'FALSE', output comes only from explicit 'print' or 'cat' statements.
    split
    logical ('FALSE'). If 'TRUE', text output is written to separate files for each code chunk.
    strip.white
    character string ('false'). If 'true', blank lines at the beginning and end of output are removed. If 'all', then all blank lines are removed from the output.
    prefix
    logical ('TRUE'). If 'TRUE' generated filenames of figures and output have a common prefix.
    prefix.string
    a character string, default is the name of the '.Snw' source file.
    include
    logical ('TRUE'), indicating whether input statements for text output and includegraphics statements for figures should be auto-generated. Use 'include = FALSE' if the output should appear in a different place than the code chunk (by placing the input line manually).
    fig
    logical ('FALSE'), indicating whether the code chunk produces graphical output. Note that only one figure per code chunk can be processed this way.
    eps
    logical ('TRUE'), indicating whether EPS figures should be generated. Ignored if 'fig = FALSE'.
    pdf
    logical ('TRUE'), indicating whether PDF figures should be generated. Ignored if 'fig = FALSE'.
    pdf.version, pdf.encoding
    passed to 'pdf' to set the version and encoding. Defaults taken from 'pdf.options()'.
    width
    numeric (6), width of figures in inches.
    height
    numeric (6), height of figures in inches.
    expand
    logical ('TRUE'). Expand references to other chunks so that only R code appears in the output file. If 'FALSE', the chunk reference (e.g. '<<chunkname>>') will appear. The 'expand=FALSE' option requires 'keep.source = TRUE' or it will have no effect.
    concordance
    logical ('FALSE'). Write a concordance file to link the input line numbers to the output line numbers. This is an experimental feature; see the source code for the output format, which is subject to change in future releases.

    AttachmentSize
    sweave_test1.png36.61 KB