The Sweave()
function is a standard R function that insert R code into a document.
To generate a .tex
document you first have to call the Sweave()
function on a .rnm
document.
\documentclass[a4paper]{article}
\begin{document}
\DefineVerbatimEnvironment{Sinput}{Verbatim}{formatcom = {\color[rgb]{0, 0, 0.56}}}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{formatcom = {\color[rgb]{0.56, 0, 0}}}
Essayons de calculer 2 + 2 :
<<options, echo = FALSE>>=
options(prompt = " ", continue = " ", width = 85)
@
<<essai2plus2>>=
2 + 2
@
\end{document}
The two \DefineVerbatimEnvironment
line define the color of the R input and ouput while the echo = FALSE
hide the corresponding R code.
The macro \Sexpr{x}
display the content of the R variable x
inside a sentence.
table with xtable
The R library xtable
can transform R table into LaTeX source code.
The following code insert a R table into a .tex
document.
\documentclass[a4paper]{article}
\begin{document}
<<options, echo = FALSE>>=
library(xtable)
x = as.data.frame(rbind(rnorm(10), rnorm(10)))
colnames(x) = 1:10
rownames(x) = 10:20
mytable = xtable(x = x, label = "tab:rnorm", caption = "some defintion of the table head")
print(mytable, file = "rnorm.tex", size = "tiny", NA.string = ".")
@
\input{rnorm.tex}
We can see some noise in the table \ref{tab:rnorm}
\end{document}
graphics
\documentclass[a4paper]{article}
\begin{document}
\SweaveOpts{prefix.string = img/data, eps = FALSE, pdf = TRUE}
\setkeys{Gin}{width=\textwidth}
Je veux une figure de 8 unites de large par 4 unites de haut
et qui tienne toute la largeur de la page dans le document final.
<<essaifig, echo = F, fig = T, width = 8, height = 4>>=
par(mfrow = c(1,2))
x = rnorm(1000)
hist(x, col = "lightblue", main = "Histogramme")
boxplot(x, col = "lightblue", horizontal = TRUE, main = "boxplot")
@
\end{document}
The line \SweaveOpts{prefix.string = img/data, eps = FALSE, pdf = TRUE}
will put every images in the folder img/
and with the prefix data
.
With this line we also set the format of the images to .pdf
.
The line <<fig1, echo = F, fig = T, width = 8, height = 4>>=
define that the R code will produce an image called fig1
of size 8 x 4.