texblog

[R/knitr] Automatic bibliography generation with biblatex in RStudio

Everybody is talking about making research reproducible. With the integration of knitr in RStudio, reproducible research has been made available to people who are less familiar with the Terminal. All you need is some basics in R and LaTeX and you can generate reports directly from within RStudio. With a few tweaks,  RStudio automatically generates the bibliography and you won’t have to manually run latex or biber/bibtex.

This post explains how to configure your .Rnw file to automatically generate the bibliography using the biblatex package in a single run from within RStudio. I assume you are familiar with RStudio and knitr/Sweave. I further assume that knitr is set as the Rnw weave option in RStudio –> Preferences –> Sweave.

 

The setup

You’ll have to do two things for the bibliography to be generated automatically (see code below),

  1. Run biblatex with the bibtex backend instead of biber. This is because RStudio uses the texi2dvi command to generate the PDF and only knows bibtex. Hopefully, this will change in the future.
  2. Set the three environment variables: TEXINPUTS, BIBINPUTS and BSTINPUTS in order to tell RStudio where to find the .tex, .bib and .bst files. Because my project was small, I had all the files in the same (root) directory. Therefore, I set the environment variables to the R working directory using getwd().
\usepackage[backend=bibtex]{biblatex}
setwd('/path/to/your/working-directory')
Sys.setenv(TEXINPUTS=getwd(),
           BIBINPUTS=getwd(),
           BSTINPUTS=getwd())

That’s all you need. Compile PDF will execute all R code chunks and generates the report with bibliography. If you use bibtex, e.g. with the natbib package, you’ll only have to set the environment variables (point 2).

 

A minimal working example
\documentclass{article}
\usepackage{hyperref}
\usepackage[backend=bibtex, sorting=none]{biblatex}
\bibliography{references}

\begin{filecontents*}{references.bib}
@Manual{knitr2013,
    title = {knitr: A general-purpose package for dynamic report
      generation in R},
    author = {Yihui Xie},
    year = {2013},
    note = {R package version 1.4.1},
    url = {http://yihui.name/knitr/},
  }
\end{filecontents*}

\begin{document}

\section*{Automatic biblatex bibliography generation in RStudio using knitr}

<<setup, include=FALSE, cache=FALSE, echo=FALSE>>=
opts_chunk$set(fig.path='figures/plots-', fig.align='center', fig.show='hold', eval=TRUE, echo=TRUE)
options(replace.assign=TRUE,width=80)
Sys.setenv(TEXINPUTS=getwd(),
           BIBINPUTS=getwd(),
           BSTINPUTS=getwd())
@

<<sample-data-hist-and-box, out.width='0.48\\textwidth'>>=
sampleData <- rnorm(1000, 0,1)
hist(sampleData)
boxplot(sampleData)
@

This document was produced in RStudio using the knitr package \cite{knitr2013} by \url{http://texblog.org}.

\printbibliography

\end{document}

Exit mobile version