I am working on RMarkdown to generate a report that includes an appendix after references. I have written the appendix on a different RMarkdown file and adapted my principal file to compile it. This is the code for my principal Rmd file that generates report:
---
bibliography: bb.bib
fontsize: 11pt
nocite: '#*'
output:
pdf_document:
includes:
after_body: Demo2.Rmd
keep_tex: yes
link-citations: true
---
\newpage
\section{Testing}\label{sec1}
```{r}
summary(cars)
```
\section{Demo}
This was done using #shiina and we will use some info from Section \ref{sec1} to do.
```{r}
summary(iris[,1:2])
```
\section{References}
The file bb.bib contains next references:
#article {shiina,
author = {Shiina, Takayuki and Birge, John R.},
title = {Stochastic unit commitment problem},
journal = {International Transactions in Operational Research},
volume = {11},
number = {1},
publisher = {Blackwell Publishing},
pages = {19--32},
year = {2004},
}
#book{groewe2001,
title={Stochastic unit commitment in hydro-thermal power production planning},
author={Gr{\"o}we-Kuska, N. and R{\"o}misch, W.},
year={2001},
series = { Preprints aus dem Institut f{\"u}r Mathematik },
publisher = { Humboldt-Universit{\"a}t zu Berlin, Institut f{\"u}r Mathematik },
}
Finally, my appendix Rmd file, Demo2.Rmd, contains this structure:
\appendix
\section*{Appendix}
\section{Additional info}
In this section we also follow #shiina to explain concepts.
Compilation works fine and generate document but issues are appearing in the appendix section. I used a reference with #shiina to cite something, but I am getting this output in the final report:
The circle in black shows that citation from bibliography is not working. Instead of #shiina, it should appear Shiina and Birge (2004). I have tried replacing Rmd file with a TeX file but it did not work.
Is it any way to correct that?, I do not know if after_body needs to be adjusted or what to do.
So, I did actually find a solution that does use some minor trickery.
---
bibliography: bb.bib
fontsize: 11pt
nocite: '#*'
output:
pdf_document:
keep_tex: true
includes:
after_body: Demo2.tex
link-citations: true
---
```{r,include=FALSE}
library(tidyverse)
rmarkdown::render('Demo2.Rmd')
a <- readChar('Demo2.tex', file.size('Demo2.tex'))
a <- a %>% str_remove('[[:space:]]*\\\\hypertarget[[\\w\\W]]+\\z') %>%
str_remove('\\A[[\\w\\W]]+begin.document.')
writeChar(a, 'Demo2.tex',eos = NULL)
```
\newpage
\section{Testing}\label{sec1}
```{r}
summary(cars)
```
\section{Demo}
This was done using #shiina and we will use some info from Section \ref{sec1} to do.
```{r}
summary(iris[,1:2])
```
\section{References}
And your Appendix-file:
---
bibliography: bb.bib
fontsize: 11pt
output:
pdf_document:
keep_tex: yes
link-citations: true
---
\appendix
\section*{Appendix}
\section{Additional info}
In this section we also follow #shiina to explain concepts.
# References
results in:
The way it works is to render the Demo2.Rmd- file before rendering the actual file and to keep the associated .tex- file.
Then the non included R-chunk cuts of all the parts we don't want to have at the end of the main file and overwrites the Demo2.tex-file.
What remains is the exact tex-code you need to have your references working.
Feels pretty dirty, but should work.
Related
First, I make two Waffleplots (I think I did it with ggplot)
(...)
waffle_school <- make_waffle(schoolsoort, StudentId)
(...)
waffle_bench <- make_waffle(schoolsoort, benchStudentId)
(...)
using some function:
make_waffle <- function(variableCol, uniqueIdentifiers, numberRowsWaffle = 5, deleteZeros=1) {
(...)
waffle <- waffle(categ_table, colors = Kleuren_schoolsoort[names(Kleuren_schoolsoort) %in% names(categ_table)], rows = numberRowsWaffle) +
theme(legend.position = "bottom") + colScale #+ guides(fill=guide_legend(ncol=4, byrow=TRUE))
return(waffle)
}
Then I actually show the plots at some point in the text
{r Waffleplot-school, fig.height = 2.5, fig.margin=TRUE, fig.cap="\\textcolor{TIGcaptioncolor}{Leerlingen per schoolsoort 21/22 op jullie school}"}
waffle_school
and
{r Waffleplot-landelijk, fig.height = 2.5, fig.margin=TRUE, fig.cap=cap1}
waffle_bench
}
which I later want to refer to in my text, by saying:
"In Figure \ref{fig:Waffleplot-school} you can see (..) and in Figure \ref{fig:Waffleplot-landelijk} you see (...)."
This leaves me with question marks in the actual reference in de pdf. By the way, I use pdflatex as a renderer.
Also, this is a part of the yaml header that my main Rmd file has, which I run from another R file.
---
output:
pdf_document:
number_sections: true
keep_tex: true
fig_caption: yes
latex_engine: pdflatex
extra_dependencies: ["flafter"]
then, I call the Rmd file with the pictures and text (incl. references) in it, which has the following header:
---
title: "SchoolInBeeld"
author: "Marja"
date: "`r Sys.Date()`"
bookdown::pdf_document2
---
I have seen the notation \#ref{}, which yielded the exact reference latex call instead of the reference itself: "\ref{fig:Waffleplot-school}". Also, I have visited many questions on this, like
Cross reference not working here, outputting in bookdown::pdf_document2 as suggested here, did not help. I changed it back to pdf_document.
cross reference in Rmd
I feel like the output format is the problem though. Something like me trying to use bookdown things but cannot figure out how to call that package.
FYI, I am fluent in Latex, but relatively new to R.
can you try this:
---
output:
bookdown::pdf_document2:
number_sections: true
keep_tex: true
fig_caption: yes
latex_engine: pdflatex
extra_dependencies: ["flafter"]
My pure-latex demo.tex is as follows:
\documentclass{article}
\usepackage[hidelinks]{hyperref}
\usepackage[numbers,super,square,sort&compress]{natbib}
\begin{document}
statistics \cite{anderson2003introduction,efron2004least,hastie2009elements}
\bibliographystyle{unsrtnat}
\nocite{*}
\bibliography{ref}
\addcontentsline{toc}{section}{References}
\end{document}
and it works well, where ref.bib contains
#Book{anderson2003introduction,
author = {Anderson, Theodore Wilbur},
publisher = {Wiley},
title = {An introduction to multivariate statistical analysis},
year = {2003},
address = {New Jersey},
edition = {3},
}
#Article{efron2004least,
author = {Efron, Bradley and Hastie, Trevor and Johnstone, Iain and Tibshirani, Robert},
title = {Least angle regression},
journal = {The Annals of Statistics},
year = {2004},
volume = {32},
number = {2},
pages = {407--499},
}
#Book{hastie2009elements,
author = {Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome},
publisher = {Springer},
title = {The elements of statistical learning: {Data} mining, inference, and prediction},
year = {2009},
address = {New York},
edition = {2},
}
#Book{fan2020statistical,
author = {Fan, Jianqing and Li, Runze and Zhang, Cun-Hui and Zou, Hui},
publisher = {CRC},
title = {Statistical foundations of data science},
year = {2020},
address = {Boca Raton},
}
I want to translate demo.tex to the rmarkdown file tex2rmd.rmd and I try
---
output:
pdf_document:
keep_tex: yes
citation_package: natbib
natbiboptions: "numbers,super,square,sort&compress"
# natbiboptions: "numbers,super,square" #test
biblio-style: unsrtnat
nocite: '#*'
bibliography: ref.bib
link-citations: yes
colorlinks: no
---
statistics [#anderson2003introduction; #efron2004least; #hastie2009elements]
# References
which gives errors like
! Missing \endcsname inserted.
<to be read again>
\&
l.351 \newcommand
\NAT#aysep{,} \newcommand\NAT#yrsep{,}
Then I check the tex2rmd.tex file from the keep_tex: yes functionality, and I find the problem happens at
\usepackage[numbers,super,square,sort\&compress]{natbib}
where there is sort\&compress instead of sort&compress. How can I fix this?
Moreover, I use natbiboptions: "numbers,super,square" instead for test purpose and find the nocite: '#*' does't work either (it should show all 4 items other than the cited 3 items). Do I ignore something?
Replacing the & from sort&compress with , solves the issue of sort&compress.
And it seems the nocite YAML key doesn't work when you use natbib or biblatex as the citation package. Because nocite key is used by pandoc-citeproc filter, but when natbib or biblatex is used as citation method (default is citeproc), pandoc-citeproc is not used then and nocite doesn't work as well.
In that case, you need to use the raw LaTeX command \nocite (as explained here)
---
output:
pdf_document:
keep_tex: yes
citation_package: natbib
natbiboptions: "numbers,super,square,sort,compress"
biblio-style: unsrtnat
bibliography: ref.bib
link-citations: yes
colorlinks: no
---
\nocite{*}
statistics [#anderson2003introduction; #efron2004least; #hastie2009elements]
# References
To avoid all the problems with rmarkdown parsing and give you much more freedom, you can directly use the latex code in rmarkdown:
---
output:
pdf_document:
keep_tex: yes
link-citations: yes
colorlinks: no
header-includes:
- \usepackage[numbers,super,square,sort&compress]{natbib}
---
\nocite{*}
statistics \cite{anderson2003introduction,efron2004least,hastie2009elements}
# References
\bibliographystyle{unsrtnat}
\bibliography{ref}
I'd like to rmarkdown::render a R document without indicating the yaml options within the document itself.
Ideally that could be an argument on rmarkdown::render or knitr::spin like what you can do to pass params (see the Rmarkdown reference book). Typically I'd like author, date and the output options too.
I think this is possible because spining the following document without specifying anything I get the following output (so there must be a template of default args that I can hopefully change)
As an example, how could I do to render a document that would give me the same output as say the below (but of course without specifying the yaml in the document ie no yaml whatsoever in the document)
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
pdf_document:
toc: true
highlight: zenburn
---
#' # Title
Hello world
#+ one_plus_one
1 + 1
You can pass yaml options as parameters too. For example:
---
params:
title: "add title"
author: "add author"
output: pdf_document
title: "`r params$title`"
author: "`r params$author`"
---
This is my document text.
Then, in a separate R script:
rmarkdown::render("my_doc.rmd",
params=list(title="My title",
author="eipi10"))
You could cat a sink into a tempfile.
xxx <- "
#' # Title
Hello world
#+ one_plus_one
1 + 1
"
tmp <- tempfile()
sink(tmp)
cat("
---
title: 'Sample Document'
output:
html_document:
toc: true
theme: united
pdf_document:
toc: true
highlight: zenburn
---", xxx)
sink()
w.d <- getwd()
rmarkdown::render(tmp, output_file=paste(w.d, "myfile", sep="/"))
I hope you are having a great time. I am working on RMarkdown for a report and I would like to ask a style related question. I am running the next code in a .Rmd file:
---
bibliography: bb.bib
fontsize: 11pt
nocite: '#*'
output: pdf_document
link-citations: true
---
\newpage
\section{Testing}\label{sec1}
```{r}
summary(cars)
```
\section{Demo}
This was done using #shiina and we will use some info from Section \ref{sec1} to do.
```{r}
summary(iris)
```
\section{References}
Everything is working fine, and I get this:
In previous graph in circle is a citation I did but I would like to change the style. In this case, only the year makes hyperlink to bibliography while the autor part Shiina and Birge does not link to bibliography.
Is it possible to adjust the style of citation so that I can have this: Shiina and Birge, 2004 with both the autor and year linked to bibliography. Or would it be possible something like this: [Shiina and Birge, 2004] because RMarkdown uses () instead of []. I do not how to set that style in RMarkdown.
The content of bb.bib file is the next:
#article {shiina,
author = {Shiina, Takayuki and Birge, John R.},
title = {Stochastic unit commitment problem},
journal = {International Transactions in Operational Research},
volume = {11},
number = {1},
publisher = {Blackwell Publishing},
pages = {19--32},
year = {2004},
}
#book{groewe2001,
title={Stochastic unit commitment in hydro-thermal power production planning},
author={Gr{\"o}we-Kuska, N. and R{\"o}misch, W.},
year={2001},
series = { Preprints aus dem Institut f{\"u}r Mathematik },
publisher = { Humboldt-Universit{\"a}t zu Berlin, Institut f{\"u}r Mathematik },
}
Many thanks for your help.
You can add a csl field to your YAML header as a link to a csl file which defines the style:
---
bibliography: bb.bib
fontsize: 11pt
nocite: '#*'
csl: cslfilename.csl
output: pdf_document
link-citations: true
---
See here for further examples. There is a long list of csl files on Github and all of them are modifiable.
I want to knit a pdf-document but the keywords don't appear in the final document. Can someone say me what I'm doing wrong?
---
title: "title"
subtitle: "subtitle"
author: "author"
date: "09 04 2019"
output:
pdf_document:
keywords: "word1, word2, word3"
footerdate: yes
abstract: 'Insert abstract here'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Introduction
When knitting to PDF, keywords are sent to the file metadata but are not actually visible in the file. Source
You can customize the template for PDF generation or render Rmd files with base_format: rticles::elsevier_article.
However, there is another way to show keywords on the PDF just by adding few codes to the Rmd file:
Add a LaTeX code to provide the \keyword command (\providecommand{\keywords}[1]{\textbf{\textit{Keywords---}} #1}) into YAML's header-includes key;
Add keywords in the text section using the LaTeX command
---
title: "title"
subtitle: "subtitle"
author: "author"
date: "09 04 2019"
output:
pdf_document:
# keywords: "word1, word2, word3" # <- You don't have to add your keywords here since they only appear as the 'invisible' metadata of PDF
footerdate: yes
abstract: 'Insert abstract here'
header-includes:
- |
```{=latex}
\providecommand{\keywords}[1]{\textbf{\textit{Keywords---}} #1}
```
---
```{=latex}
\keywords{word1, word2, word3}
```
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Introduction