Sweave is a tool for embedding R code in a LaTeX file. Pweave is an analogous tool for Python. By putting your code in your document rather than the results of running your code somewhere else, results are automatically recomputed when inputs change. This is especially useful with graphs: rather than including an image into your document, you include the code to create the image.
To use either Sweave or Pweave, you create a LaTeX file and include source code inside. A code block begins with <<>>=
and ends with @
on a line by itself. By default, code blocks appear in the LaTeX output. You can start a code block with <<echo=FALSE>>=
to execute code without echoing its source. In Pweave you can also use <%
and %>
to mark a code block that executes but does not echo. You might want to do this at the top of a file, for example, for import
statements.
Sweave echos code like the R command line, with >
for the command prompt. Pweave does not display the Python >>>
command line prompt by default, though it will if you use the option term=TRUE
in the start of your code block.
In Sweave, you can use Sexpr
to inline a little bit of R code. For example, $x = Sexpr{sqrt(2)}$
will produce x = 1.414…. You can also use Sexpr
to reference variables defined in previous code blocks. The Pweave analog uses <%=
and %>
. The previous example would be $x = <%= sqrt(2) %>$
.
You can include a figure in Sweave or Pweave by beginning a code block with <<fig=TRUE, echo=FALSE>>=
or with echo=TRUE
if you want to display the code that produces the figure. With Sweave you don’t need to do anything else with your file. With Pweave you need to add usepackage{graphicx}
at the top.
To process an Sweave file foo.Rnw
, run Sweave("foo.Rnw")
from the R command prompt. To process a Pweave file foo.Pnw
, run Pweave -f tex foo.Pnw
from the shell. Either way you get a LaTeX file that you can then compile to a PDF.
Here are sample Sweave and Pweave files. First Sweave:
\documentclass{article}
\begin{document}
Invisible code that sets the value of the variable $a$.
<<<echo=FALSE>>=
a <- 3.14
@
Visible code that sets $b$ and squares it.
<<bear, echo=TRUE>>=
b <- 3.15
b*b
@
Calling R inline: $\sqrt{2} = Sexpr{sqrt(2)}$
Recalling the variable $a$ set above: $a = Sexpr{a}$.
Here's a figure:
<<fig=TRUE, echo=FALSE>>=
x <- seq(0, 6*pi, length=200)
plot(x, sin(x))
@
\end{document}
And now Pweave:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
<%
import matplotlib.pyplot as plt
from numpy import pi, linspace, sqrt, sin
%>
Invisible code that sets the value of the variable $a$.
<<echo=FALSE>>=
a = 3.14
@
Visible code that sets $b$ and squares it.
<<term=True>>=
b = 3.15
print b*b
@
Calling Python inline: $\sqrt{2} = <%= sqrt(2) %>$
Recalling the variable $a$ set above: $a = <%= a %>$.
Here's a figure:
<<fig=True, echo=False>>=
x = linspace(0, 6*pi, 200)
plt.plot(x, sin(x))
plt.show()
@
\end{document}
Related links