Rmarkdown PDF citations not rendering correctly (csl issue?) - r-markdown

I'm getting to grips with writing publications in rmarkdown. No issues at all generating .html files, or .docx files, but when I generate .pdf files the citations don't seem to inherit the style defined in the .csl file.
For example, with a numbered .csl style I expect:
[#Author_Title_2003] -> (1)
Which is successful in .html and .docx files, but in .pdfs I get:
[#Author_Title_2003] -> [Author, 2003]
With square brackets printed as well.
An example:
test.rmd:
---
title: 'My Title'
author: "Me me me me!"
output: pdf_document
bibliography: references.bib
csl: elsevier-vancouver.csl
---
Application written in the R programming language [#RCoreTeam] using the Shiny framework [#Chang2015].
# REFERENCES
references.bib:
#Misc{Chang2015,
Title = {shiny: Web Application Framework for R. R package version 0.12.1},
Author = {Chang, W. and Cheng, J. and Allaire, JJ. and Xie, Y. and McPherson, J. },
Year = {2015},
Type = {Computer Program},
Url = {http://CRAN.R-project.org/package=shiny}
}
#Article{RCoreTeam,
Title = {R: A Language and Environment for Statistical Computing},
Author = {{R Core Team}},
Year = {2015},
Type = {Journal Article},
Url = {http://www.R-project.org}
}
elsevier-vancouver.csl: link
running rmarkdown::render("test.Rmd", "pdf_document") gives:
/home/jordan/.cabal/bin/pandoc +RTS -K512m -RTS paper.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-implicit_figures --output paper.tex --template /home/jordan/R/x86_64-pc-linux-gnu-library/3.2/rmarkdown/rmd/latex/default-1.14.tex --highlight-style tango --latex-engine pdflatex --natbib --variable graphics=yes --variable 'geometry:margin=1in' --bibliography references.bib
And the output file is:
See the incorrectly formatted citations. Also note this format is generated regardless of the csl argument in the header. Any help would be much appreciated.
pandoc version 1.15.2.1, pandoc-citeproc version 0.8.1.3.

So I figured out what was going on after a) reading the rmarkdown package code and b) getting to know latex a bit better. I thought I'd post my answer here in case anyone has a similar problem.
In short, rmarkdown generates a .tex file from the .rmd file, and then processes the .tex file using latexmk (or a similar R system call). Latex engines of course don't actually use .csl style files, instead bibtex uses .bst files.
In short, for formatted references in a .pdf document (generated from .rmd) either:
Create a .bst file with the required format, and convert the .tex
file produced by R(Studio) manually.
Convert the .tex file to pdf using pandoc again, which can use .csl
files in the process. This does seem to remove hyperlinking,
however.

Related

Using relative paths in Rmarkdown when knitting from two different locations

My problem is with use of relative links and "compiling" (knitting).
I'm writing a book using RMarkdown. Since the file will be relatively large, I need to split into subfiles and directories.
I have a masterfile which only includes links to chapters(chap1, chap2, ...). There is a file for each chapter and each needs references to some figures (fig1,...).
I would like to be able to knit masterfile.Rmd and chap1.Rmd independently from each others so to get one file for chapters, and one file for the whole book.
Here is how my files are organized (MVE). Directories are displayed in upper case.
ROOT
masterfile.Rmd
FIGURES
fig1.pdf
fig2.pdf
CHAPTERS
chap1.Rmd
chap2.Rmd
...
The code of masterfile.Rmd is as follows:
{r child = '/chapters/chap1.Rmd'}
The code of chap1.Rmd is as follows:
![](../figures/fig1.pdf)
As I knit from chap1.Rmd, everything is fine. As I knit from masterfile, I get the following message:
[WARNING] Could not fetch resource '../figures/fig1.pdf': PandocResourceNotFound "../figures/fig1.pdf"
It seems that fig1.pdf cannot be found. I guess that this is because the include statement in master file only "copies" the code of chap1.Rmd and "executes" it in the ROOT directory (not in the CHAPTERS directory) so ".." drives to location that does not exist (before ROOT) when knitted from masterfile.
I could change the setting and write ![](/figures/fig1.pdf) in chap1.Rmd file. It would work fine when knitting from masterfile but no longer from chap1.Rmd.
Do you know how to have both?
Welcome to the RMarkdown community!
Due to KnitR, Rmd, and pandoc inter-workings, this is not as easy of a solution as you'd think, but a directory restructure would almost be easier.
Even if you look at Rmarkdown author's newest book RMarkdown CookbookHERE. They have all the chapters in the ROOT directory, and only sub directories for images(and possibly figures).
resources:
1. Other SO similar question
2. Github options knitr question
3. similar question from Rstudio community
You can make use of the Lua filter feature to rewrite image paths when knitting the main file. E.g.
function Image (img)
img.src = img.src:gsub('^%.%./', './')
return img
end
This will replace a path like ../figures/fig1.pdf with ./figures/fig1.pdf.
Use the code writing it to a file and calling adding it via pandoc_args (in the main file only).
---
output:
html_document:
pandoc_args: ["--lua-filter=filter.lua"]
---

Rmarkdown rticles - MDPI template. How to print your own abbreviations

I am using the MDPI template (from the rticles package), and keen to also use the glossaries packages so I don't have to manually feed all the abbreviation on the appropriate YAML field.
For such, I have loaded the LaTex package glossaries using the header-includes:
header-includes:
\usepackage{inputenc}
\usepackage[acronym, section=section]{glossaries}
\setacronymstyle{long-short}
\makeglossaries
\makeindex
\input{glossary}
after creating several acronyms within the Rmarkdown body, I would be willing to either input the latex commands and have it printed in within the "Abbreviations" section of the template.
Currently, I am able to hack it through the following steps (I am sure there is a better way):
1- keep all the aux files chunk with :
options(tinytex.clean = FALSE)
2- cmd makeglossaries "filename"
3- Raw Latex on Rmarkdown file:
\begin{abbreviations}
\setabbreviationstyle[acronym]{long-short}
\printglossary[type=\acronymtype,title={}]
\end{abbreviations}
However, I would be keen to know if I could insert something on the YAML and use the MDPI formatting.
Alternatively, I could edit the rticles MDPI template (but I am not sure how).
Any ideas?
Cheers,
Include in YAML:
include-after: glossary.tex
I tried without success, but it seems reasonable that this approach might work with a few modifications

Chapter(s) before table of contents in Bookdown PDF output

I'd like for a chapter to appear before the table of contents (but after the title page) in the pdf_book output of Bookdown.
One way to do this is to add the chapter to a .tex file and and link it using before_body:. However, this means the chapter will not appear in gitbook (which I also need). I'd prefer not to keep both a .tex and .Rmd version of the same chapter.
An ideal solution would be if the chapter could be kept in a .Rmd file, and its contents extracted into the before_body for pdf_book. That way it's still available for gitbook. Though I'm not sure how I might do that, or indeed if it's possible?
Is there a solution? Or is it exceeding the limits of Bookdown's flexibility?
Any help would be greatly appreciated, thanks!
One can trigger ToC creation manually in the document, which gives more control over its placement. Of course, automatic table of contents creation should be disabled:
---
title: "MWE"
output:
bookdown::pdf_book:
toc: False
---
```{r child = 'file-you-want-to-include.Rmd'}
```
```{=latex}
% Trigger ToC creation in LaTeX
\tableofcontents
```
# Rest of your document starts here
The downside is that this only works with PDF output, not HTML.

Use additional Latex packages for math expressions in RMarkdown `output = "html_document"`

I`m aware how to use additional Latex-packages for pdf-format output from .Rmd files using
---
header-includes:
- \usepackage{mathtools}
---
in the YAML header.
However, this does (of course) not work if one specifies output: html_document.
---
output: html_document
header-includes:
- \usepackage{mathtools}
---
Using additional Latex-Packages could be of interest for output: html_document, too - especially in math expressions (MWE below)
---
title: "MWE"
output: html_document
header-includes:
- \usepackage{mathtools}
---
## Use "Defined by" Symbol
$$sin(x) \coloneqq \frac{opposite}{hypothenuse}$$
MathJax offer a number of extensions, and there are third-party extensions as well. If your desired package is not available in this way, then things get difficult.
Simple commands, such as \coloneqq, can be recreated using \newcommand. The simplest way is to add these via the include-before option. Using your MWE with a solution from Mathematics Meta SE, one gets:
---
title: "MWE"
output:
html_document: default
include-before:
- '$\newcommand{\coloneqq}{\mathrel{=}}$'
---
## Use "Defined by" Symbol
$$sin(x) \coloneqq \frac{opposite}{hypothenuse}$$
Output:
Background
RMarkdown is build around pandoc, which performs most of the format conversions. Pandoc creates PDF via LaTeX (by default), and will simply include any raw LaTeX commands which are given in the source. When seeing \usepackage{mathtools}, the package is not parsed, but the command is simply added verbatim to the intermediate LaTeX. However, when exporting to HTML, it wouldn't make sense to pass through LaTeX commands, so any such command will simply be omitted from the output, so any \usepackage in your document won't effect the HTML output.
Alternative solution
If you are using very complex LaTeX-packages, then you could consider setting up a complex pipeline to still use it: E.g, one could use a pandoc filter to extract all equations, compile each equation as a separate document, and then convert the resulting PDF to SVG. Finally, that SVG can then be included in the HTML output. This is non-trivial and probably not worth the effort. A similar approach is recommended to include TikZ pictures.

Compiling reveal.js-based R markdown presentation without RStudio

Fairly recently, RStudio has added support for beautiful reveal.js-based HTML presentations generated from RMarkdown (with some extensions). These are different from earlier HTML presentation formats provided by the rmarkdown R package, which relied on ioslides or Slidy.
Is it possible to compile such a presentation to HTML without having recourse to RStudio? I.e. is there a pure R function which will, given an R presentation source file, generate the same result as the IDE?
P.S. I suppose the underlying R package doing the conversion is revealjs by JJ Allaire, but on its own, it doesn't recognize some of the syntax extensions (e.g. those for customizing appearance by putting css: custom.css under the title of the first slide), which makes me think there must be an additional wrapper around it.
You can use the standard rmarkdown::render() function with the revealjs::revealjs_presentation format in the YAML header. Resources like custom.css are referenced relative to the Rmd location so there is no need to specify these within the render() step.
User notes on specific implementation diffs between native RStudio & scripted version
It's not a drop-in replacement though. The revealjs package, as it's available from CRAN, ships with a different (newer) version of the reveal.js library than the one used internally by RStudio (3.2 vs 2.4 as of March 8th, 2016). The default settings (e.g. transitions) are also different, so they need tweaking.
Circumspection is also warranted with the version of pandoc used as the workhorse for the Markdown → HTML conversion, as RStudio may internally be using an older one with different templates. All of this means that you may need to rework your customizations (e.g. css tweaks).
There are also syntax differences -- the metadata can't go under the first heading of the presentation (i.e. the title):
Presentation title
==================
author: Foo Bar
css: custom.css
Instead, they have to be put in a traditional RMarkdown YAML header:
---
author: Foo Bar
css: custom.css
---
I'm not sure whether per-slide special settings like incremental: true (which are put under the respective slide's heading in the RPresentation format) are recognized at all.
I use a script like this that I source to render my reveal.js markdown slides:
library(rmarkdown)
library(revealjs)
file.name <- "index"
path.to.file <- "."
rmarkdown::render(file.path(path.to.file, paste0(file.name, ".Rmd")),
revealjs_presentation(theme="white", highlight="tango", slideNumber = TRUE),
encoding = "UTF-8")
# Open the generated HTML file in the browser
browseURL( file.path(path.to.file, paste0(file.name, ".html")))