Search code examples
rknitrbibtexbibliography

Bibliography in knitr child documents


I am having trouble including a bibliography in a knitr child document. I want to be able to reference articles from my main bibliography in a child document, but have the bibliography appear after the main document, not after the child. If I only include the \bibliography command in the main document, the references in the child document are not parsed correctly. Example:

main.Rnw:

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\begin{document}
This is the main doc.

<<child-demo, child='child.Rnw'>>=
@
\bibliography{mylib}
\end{document}

child.Rnw:

This is the child \cite{myref}.

mylib.bib:

@article{myref,
 title = {frobnosticating froo filters}
 volume = {21},
 journal = {Frobnification},
 author = {John Q. Smith}
 month = jan,
 year = {2004}
}

My compile script contains:

#!/usr/bin/env Rscript
library(knitr)
knit('main.Rnw', tangle=TRUE)
knit('main.Rnw', tangle=FALSE)
for ( i in c(1,2,3)) {
  system('pdflatex main')
  system('bibtex main')
}

Running compile produces:

out

How can I make the child document include references from the main bibliography?


Solution

  • First, you missed a few commas in your mylib.bib:

    @article{myref,
     title = {frobnosticating froo filters},
     volume = {21},
     journal = {Frobnification},
     author = {John Q. Smith},
     month = {jan},
     year = {2004}
    }
    

    Then you did not specify a bibliography style:

    \documentclass[10pt,a4paper]{article}
    \usepackage[utf8]{inputenc}
    \begin{document}
    This is the main doc.
    
    <<child-demo, child='child.Rnw'>>=
    @
    \bibliography{mylib}
    \bibliographystyle{plain}
    \end{document}