I am trying to write my PhD Thesis with bookdown and am mainly using pdf output. I have easily added a bibliography at the end of the document but would rather have a bibliography at the end of each chapter. I have tried adjusting the .tex output with LaTeX packages that allow this but this fights with the bookdoown defaults. Is there a way of adapting the .yaml options to enable this?
For HTML output the default is to use per-chapter bibliographies. For PDF output, I have found it is best to use the LaTeX package biblatex together with biber. Since RStudio does not know about biber, it is best to install a tool like latexmk and configure RStudio to use that via Sys.setenv(RSTUDIO_PDFLATEX = "latexmk"). These programs might have to be installed separately, e.g. on Debian/Ubuntu/...
sudo apt-get install texlive-bibtex-extra biber latexmk
For configuring biblatex the solution provided at https://tex.stackexchange.com/questions/199336/biblatex-reference-both-by-chapter-and-at-the-end-of-the-book is appropriate.
In the end the following settings are necessary in _output.yml:
bookdown::pdf_book:
citation_package: biblatex
In Index.Rmd:
biblio-style: authoryear
biblatexoptions: [refsegment=chapter]
At the end of every chapter:
\printbibliography[segment=\therefsegment,heading=subbibliography]
There is no need to escape this raw LaTeX command, since pandoc ignores such commands for other output formats.
One can see the entire solution at
https://github.com/rstub/bookdown-chapterbib
https://rstub.github.io/bookdown-chapterbib/
https://rstub.github.io/bookdown-chapterbib/bookdown-chapterbib.pdf
Original solution
I managed to get chapter bibliographies with PDF output using the following steps:
Start with a copy of https://github.com/rstudio/bookdown-demo
copy <R-library-path>/rmarkdown/rmd/latex/default-1.17.0.2.tex as book.tex to the working directory
update book.tex to use the LaTeX package bibunits (diff below)
update _output.yml to refer to book.tex as template (diff below)
set YAML options in index.Rmd (diff below)
add code to some Rmd files to write \putbib command (diff below)
After these changes, a PDF file could be produced, but all references where missing, since bookdown does not know about the generated bu?.aux files. After executing bibtex bu1 and bibtex bu2, reproducing the PDF file via bookdown produced a PDF with chapter bibliographies. It is probably best to automate this step with Makefile.
Here the diff between the templates:
$ diff -u /usr/local/lib/R/site-library/rmarkdown/rmd/latex/default-1.17.0.2.tex book.tex
--- /usr/local/lib/R/site-library/rmarkdown/rmd/latex/default-1.17.0.2.tex 2017-12-11 19:14:54.643867696 +0100
+++ book.tex 2018-01-16 11:43:46.182542634 +0100
## -93,8 +93,11 ##
\fi
$endif$
$if(natbib)$
-\usepackage{natbib}
+\usepackage[$natbiboptions$]{natbib}
\bibliographystyle{$if(biblio-style)$$biblio-style$$else$plainnat$endif$}
+\usepackage{bibunits}
+\defaultbibliographystyle{$if(biblio-style)$$biblio-style$$else$plainnat$endif$}
+\defaultbibliography{$for(bibliography)$$bibliography$$sep$,$endfor$}
$endif$
$if(biblatex)$
\usepackage$if(biblio-style)$[style=$biblio-style$]$endif${biblatex}
## -235,6 +238,7 ##
$endfor$
\begin{document}
+\bibliographyunit[\chapter]
$if(title)$
\maketitle
$endif$
And the diff of the files from bookdown-sample:
$ git diff
diff --git a/01-intro.Rmd b/01-intro.Rmd
index 6b16e73..1a5f9de 100644
--- a/01-intro.Rmd
+++ b/01-intro.Rmd
## -19,3 +19,5 ## knitr::kable(
```
You can write citations, too. For example, we are using the **bookdown** package [#R-bookdown] in this sample book, which was built on top of R Markdown and **knitr** [#xie2015].
+
+`r if (knitr:::is_latex_output()) '\\putbib'`
diff --git a/02-literature.Rmd b/02-literature.Rmd
index 00745d0..983696e 100644
--- a/02-literature.Rmd
+++ b/02-literature.Rmd
## -1,3 +1,6 ##
# Literature
Here is a review of existing methods.
+[#R-knitr]
+
+`r if (knitr:::is_latex_output()) '\\putbib'`
diff --git a/_output.yml b/_output.yml
index 342a1d6..cc8afb1 100644
--- a/_output.yml
+++ b/_output.yml
## -14,4 +14,5 ## bookdown::pdf_book:
latex_engine: xelatex
citation_package: natbib
keep_tex: yes
+ template: book.tex
bookdown::epub_book: default
diff --git a/index.Rmd b/index.Rmd
index 4e21b9d..2fdb813 100644
--- a/index.Rmd
+++ b/index.Rmd
## -7,6 +7,8 ## output: bookdown::gitbook
documentclass: book
bibliography: [book.bib, packages.bib]
biblio-style: apalike
+natbiboptions: sectionbib
+graphics: yes
link-citations: yes
github-repo: rstudio/bookdown-demo
description: "This is a minimal example of using the bookdown package to write a book. The output format for this example is bookdown::gitbook."
For a latex-specific solution see this post, i.e. use the sectionbib option for natbib and load the chapterbib package. You will need to edit The bookdown template to set the required options for natbib and tell bookdown to use your custom template in the yaml. See this post for more info on the bookdown template.
I swear I saw instructions in the bookdown docs for doing this with gitbook format, but I can't seem to find it...
EDIT I went and looked at an old bookdown project of mine. For gitbook output, you specify the following in _output.yml:
bookdown::gitbook:
split_by: chapter
split_bib: yes
Which will (you guessed it) split the bibliography by chapter. I'm actually a bit surprised that bookdown doesn't support the equivalent options for bookdown::pdf_book yaml options, but should be easy enough to do by setting up sectionbib/chapterbib in the LaTeX preamble.
Related
I am using bookdown package in R to compile a bookdown::pdf_book. But I am unable to knit it when I use authblk latex package. The strange thing is that I can compile the same thing outside of RStudio, even when I am using authblk latex package. Let me share a minimal example here.
Preamble taken from TeXStudio
\documentclass[a4paper,12pt]{book}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{authblk}
\begin{document}
\author[1]{First Author Name}
\author[2]{Second Author Name}
\affil[1]{College1}
\affil[2]{College2}
\title{Simple Book Example}
\date{January 2013}
\frontmatter
\maketitle
\tableofcontents
\mainmatter
\include{./TeX_files/chapter01}
\include{./TeX_files/chapter02}
\backmatter
% bibliography, glossary and index would go here.
\end{document}
YAML Header from Index.Rmd page
title: "A Minimal Book Example"
author: "Author Name"
affil: "College 1"
date: "`r Sys.Date()`"
output: pdf_document
documentclass: book
bibliography:
- book.bib
- packages.bib
description: |
This is a minimal example of using the bookdown package to write a book.
set in the _output.yml file.
The HTML output format for this example is bookdown::bs4_book,
site: bookdown::bookdown_site
---
YAML header from _output.yml file
bookdown::pdf_book:
includes:
in_header: preamble.tex
latex_engine: pdflatex
citation_package: biblatex
keep_tex: yes
Latex code in preamble.tex
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{authblk}
The problem is that when I knit (or Build pdf_book) from RStudio, the college name is not seen in the title page of the PDF book. I have tried various ways, but I am getting one or the other errors. I want to show two authors (along with their respective affiliation) on the title page of the book. But here, I can't display it even for one author when I compile it through TinyTeX in RStudio. However, when I compile the TexStudio code in TeXStudio using TinyTeX, it displays two authors and their affiliations correctly. How can I solve this?
I used to be able to render images in r-markdown using a URL with the following code ![](https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark) but I get a file not found error ! LaTeX Error: File https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark' not found.
Am I missing packages? This code still works on some shiny apps published a few month ago.
Below the a working file r-markdown file:
---
title: "Test"
header-includes:
- \usepackage{graphicx}
output:
pdf_document:
latex_engine: xelatex
number_sections: yes
keep_tex: yes
classoption: article
papersize: A4
fontsize: 10pt
geometry: margin=0.9in
linestretch: 1.15
---
## R Markdown
![](https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark)
The LaTeX graphicx package does not include an http client, it is therefore not able to pull the image from the internet. However, a lot of the conversion work from Markdown to LaTeX is performed by pandoc, which can get this image. One just needs to tell pandoc to store all images locally by passing the --extract-media option. This allows LaTeX to find the images when it is invoked by RMarkdown.
---
output:
pdf_document:
pandoc_args: ["--extract-media", "."]
---
The above will store all images in the same directory as the Rmd file. The files will be named using SHA1 hashes, so you might want to use a separate directory for these files instead.
If I set an output parameter in .Rmd file in following way:
output:
bookdown::pdf_book:
base_format: rticles::elsevier_article
keep_tex: true
in the produced .tex file, endfloat package will be used with option 'nomarkers'. In other words, following line will be included in produced .tex file:
\usepackage[nomarkers]{endfloat}
How can I set options for LaTeX packages used by the output?
In my example, I wish to set endfloat options to 'markers', so that mentioned line in .tex file will looks as follows:
\usepackage[markers]{endfloat}
The simple solution
header-includes:
- \usepackage[markers]{endfloat}
output:
bookdown::pdf_book:
base_format: rticles::elsevier_article
keep_tex: true
works not, because there are package conflicts. The other solution I tried and worked, was to download the package from GitHub https://github.com/rstudio/rticles and change the file template.tex to your needs. This file is located in /inst/rmarkdown/templates/elsevier_article/resources/. For me this worked and the .tex file has the desired output as you expect it.
I'm trying to run inline R code in the YAML front matter before getting rmarkdown to run the file. However it isn't working for me. Here's an example:
---
title: "**Title**"
classoption: xcolor=dvipsnames
output:
beamer_presentation:
slide_level: 2
pandoc_args: [
"--bibliography", "`r paste('path/to/bib')`"
]
---
<!-- slide 1 -->
## Intro ##
Which throws an error:
pandoc-citeproc: could not find `r paste('path/to/bib')`
This is a simple example, but highlights my main problem. How do I get rmarkdown to run the inline R code in the YAML front matter?
It is a similar problem to these questions:
Manipulate RMarkdown metadata from within R code chunks
YAML current date in rmarkdown
This is how I solved this. I knit from RStudio. Curiously, I had to use one solution for the date and csl fields and a different solution for the bibliography field. !expr did not work in the date or csl lines (for me). And quoted r code didn't work in the bibliography line (for me). I have the bibliography and csl files in a package (inst/docs folder). rmarkdown files, which are not part of that package, use those.
---
title: "Title"
date: '`r format(Sys.time(), "%d %B, %Y")`'
output: html_document
bibliography: !expr system.file("docs", "my.bib", package = "MyPackage")
csl: '`r system.file("docs", "my.csl", package = "MyPackage")`'
---
# Introduction
Yada yada [#MyRef04].
# References
my.bib is the BibTex file with MyRef04. csl is the style file
This is a situation where one person maintains a package which has data, code, bibliography, etc. Others, potentially unknown to the package writer, install that package from GitHub and write or run rmarkdown files that use the package. The users almost certainly do not use Git or GitHub and I don't want them to have to download any extra files after installing the package from GitHub.
Update: After posting the above, I happened to install markdown from GitHub because I needed something in the development version. With version ‘1.7.5’ of rmarkdown on GitHub you can use r code in the bibliography line:
---
title: "Title"
date: '`r format(Sys.time(), "%d %B, %Y")`'
output: html_document
bibliography: '`r system.file("docs", "my.bib", package = "MyPackage")`'
csl: '`r system.file("docs", "my.csl", package = "MyPackage")`'
---
To install rmarkdown from GitHub
library(devtools)
install_github("rstudio/rmarkdown")
So I found a round about way of getting what I wanted. Rmarkdown I don't think allows R expressions/commands in the YAML, probably for a good reason. What I ended up doing was putting all the output yaml commands in a file called _output.Ryaml like so:
beamer_presentation:
slide_level: 2
includes:
in_header: "src/preamble.tex"
pandoc_args: [
"--bibliography", "`r paste('path/to/bib')`",
"--variable", "classoption:xcolor=dvipsnames",
"--variable", "fontsize:9pt"
]
Then in the main slides.Rmd file, was something like:
---
title: "**Title**"
author: Luke
---
<!-- slide 1 -->
## Intro ##
Then, I can generate the slides using the R code (which I put into a Makefile):
knitr::knit('_output.Ryaml', '_output.yaml')
rmarkdown::render('slides.Rmd')
unlink('_output.yaml')
Seems to be working well enough. If anyone's got a better idea, let me know!
I am using knitr, R markdown, and a custom LaTeX file to write a manuscript. The abstract is set as part of the YAML frontmatter. This works great, except that the results that I would like to include in the abstract are generated later in the document.
Having the abstract in the YAML makes some sense to me and I would prefer to keep it this way. Any thoughts on a way to have the abstract take advantage of calculations that happen later in the document?
A brief example:
---
title: 'How do I interpret R objects in YAML that are created in the document?'
author: Jeff Hollister
output:
pdf_document:
fig_caption: yes
keep_tex: yes
number_sections: yes
html_document: null
word_document: null
fontsize: 11pt
documentclass: article
abstract: This is a test. Is this `r mean(x)` working?
---
This is a test of outputing a pdf, with R code interpretted in the YAML front mater. Use case
for this would be a manuscript, with abstract as part of YAML, and some of the results in the
abstract being calculated in the body of the Rmd. For instance:
```{r}
x<-rnorm(100)
mn<-mean(x)
mn
```
It's not exactly YAML-related, and limited to latex, but maybe this helps. Sorry, the thread is in German, but maybe the code is clear enought.
You can pick items for the abstract as you create your report; the items are written out to a temporary file similar to method use in bibtex and biblatex, and merged to the start and end (for appendix) in a second step.
As a package, you can download it from here .
Requirements
Install R, knitr, and yaml:
sudo su -
apt-get install pandoc
apt-get install r
r
url <- "http://cran.us.r-project.org"
install.packages('knitr', repos=url)
install.packages('yaml', repos=url)
Create Variables
Separate the variables into a new file (e.g., v.yaml):
title: 'How do I interpret R objects in YAML that are created in the document?'
author: Jeff Hollister
output:
pdf_document:
fig_caption: yes
keep_tex: yes
number_sections: yes
html_document: null
word_document: null
fontsize: 11pt
documentclass: article
abstract: This is a test. Is this `r mean(x)` working?
Create Script
Create a script to load knitr, yaml, and the variables (e.g., knitr.sh), when given a file in Markdown format:
#!/bin/bash
R -e \
"library(knitr); library(yaml); v <- yaml.load_file('v.yaml'); knit('$1')"
Reference Variables
Use R statements (inline or otherwise) to reference the source document variables (document.md):
# `r v$title`
Author: `r v$author`
Run Script
Generate a knitr-processed Markdown file by running the script:
./knitr.sh document.md
View Output
The file document.txt (renaming is a problem left for the reader) should contain the following Markdown:
# How do I interpret R objects in YAML that are created in the document?
Jeff Hollister
Addendum
It is fairly trivial with shell script magick to insert the variables at the top of the generated file, should they be needed for processing by pandoc. If using YAML variables for pandoc's templates, I'd recommend skipping that route and using R variables instead.