13.1 Sweave: R code in LaTex

To start, we create a new .Rnw file.

Go to File > New File > R Sweave to open a new file.

You can see \documentclass{article} and \begin{document} at the beginning of the file and \end{document} at the end of the file.

This is standard LaTeX document. Hence, we can work it as standard LaTeX file.

Let us type something and click compile.

\documentclass{article}
\begin{document}

Hello World!

\end{document}

There are two ways to incorporate R code:

  1. inline: \Sexpr{}
\documentclass{article}
\begin{document}

I have 2 apples. You have 3 apples. 

Hence, we have \Sexpr{2+3} apples.

\end{document}
  1. display: start with << >>=, and end with @
\documentclass{article}
\begin{document}

I have 2 apples. You have 3 apples.

<< >>=
x <- 2
y <- 3
cat('We have ', x+y, 'apples.')
@

\end{document}