## Saturday, February 7, 2015

### Writing Books with R and knitr

I am writing this post on behalf people who, like me, do not find any valuable stuff in the web, when trying to compile big documents in R with the knitr library.

knitr is a basic tool for the statistician. It combines LaTeX and R in an single environment. It is useful to create elegant reports, papers, and related stuff. You gotta have RStudio for knitr to run. You can find a lot of examples, manuals, etc. in the web. However, when it comes to write big documents, such as books, or thesis, the stuff you can find on the web is limited.

First, the goal is to compile a book, with two chapters and the bibliography. You gotta create three different files (.Rnw). In RStudio, open three files in File - New File - R Sweave. One file is destined to be the main file where you will compile the book. The remaining files are just the two chapters. You must have a .bib file, for your references to be created. These files must be in the same folder in your PC (or MAC).

So, the main file will contain the basic LaTeX packages for your document to run. In this particular case, I just need Harvard for the references. The class of the document must be book (or some other class that allows chapter environment). From this main file, we will call the chapters to compile the book. So, the body of this file is as follows:

\documentclass{book}
\usepackage[full]{harvard}
\begin{document}
\bibliographystyle{agsm}

\Sexpr{knit_child('cap1.Rnw')}
\Sexpr{knit_child('cap2.Rnw')}

\bibliography{LibroBib}
\end{document}

You may notice that the code knit_child is calling the chapters of the book. Having said that, we must write the chapters and save it with a proper name. In this particular case, I will save them as cap1.Rnw and cap2.Rnw. The content of cap1.Rnw is as follows:

\chapter{Intro}

This chunk below is from the child document.
<<cap1, out.width='2in'>>=
1+1
rnorm(5)
plot(1)
boxplot(1:10)
str(mtcars)
@

In this first chapter I included some R code and some graphics. The content of cap2.Rnw is:

\chapter{Basic Stuff}

This chunk below is from the child document.
<<cap2, out.width='2in'>>=
x <- c(1, 2, 3)
w <- c(0.5, 0.4, 0.1)
sample(x, 10, replace = T, prob = w)
@

\citeasnoun{Loh} says that the best sampling scheme is not yet invented.

In this second chapter I included some references. Finally the bibliography file, that is called LibroBib.bib, contains the some references. After compilation this is the final PDF.

#### 1 comment:

1. Thanks! This post helped me a lot!