RMarkdown: Floating TOC AND TOC at the start of the report - r

I want to have both: a floating TOC and a TOC at the start of the report (in Rmarkdown). I think it's only possible to have one.
Here, I have manually added a TOC.
---
title: "Report"
author: "Anon"
date: '2022-07-20'
output:
html_document:
toc: true
toc_float: true
toc_depth: 2
collapsed: true
smooth_scroll: true
---
## Table of Contents
- R Markdown
- Including Plots
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
## Including Plots
You can also embed plots, for example:
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
I followed this question but I can either have a floating TOC OR a TOC at the beginning. I want both. It's one of the requirement by a client.

The template that html_document uses can't do this, but it's easy to edit it to allow for both.
To find the default template, use
system.file("rmd/h/default.html", package = "rmarkdown")
Get a copy of that file in the editor, and find these lines:
$if(toc_float)$
$else$
$if(toc)$
<div id="$idprefix$TOC">
$if(toc-title)$
<h2 id="$idprefix$toc-title">$toc-title$</h2>
$endif$
$toc$
</div>
$endif$
$endif$
Change them to
$if(toc)$
<div id="$idprefix$TOC">
$if(toc-title)$
<h2 id="$idprefix$toc-title">$toc-title$</h2>
$endif$
$toc$
</div>
$endif$
(i.e. make the block unconditional, instead of conditioning on not having toc_float set.) Save this file, e.g. to "toc2.html".
In the YAML for your document, add the option to specify this template, i.e. it should be
output:
html_document:
toc: true
toc_float: true
toc_depth: 2
collapsed: true
smooth_scroll: true
template: toc2.html
That should do it!

Related

How can I control the location of the table of contents in R Markdown (PDF output)?

The YAML header:
---
subtitle: "subtitle"
title: "title"
output:
pdf_document:
toc: true
toc_depth: 2
number_sections: true
---
This places the table of contents at the very beginning of the document but I would like to have it after the two first pages.
Does anyone know how to manage this? I would prefer not to use too much LaTeX.
If the first two pages shoud contain static content (not generated in the body of the R Markdown document), then moving the table of contents to page 3 can be achieved with small modifications in the LaTeX template used by Pandoc.
As explained in The Cookbook, the default LaTeX template is this (latest version).
Download that file and save it in the directory of your RMD file. In my example below I named the file toc-at-page3-template.tex.
Edit the template: For example, after line 476 (i.e., before $if(toc)$), add
\begin{center}
Custom Stuff
\end{center}
\clearpage
\begin{center}
More Custom Stuff
\end{center}
\clearpage
In your RMD file, enable the custom template:
output:
pdf_document:
toc: true
template: toc-at-page3-template.tex
---
Foo.
Output:
(click on thumbnails to enlarge)

Specify paths to custom theme, preamble and includes in YAML-header of beamer presentation generated with R markdown

In a beamer presentation generated with rmarkdown::beamer_presentation, my aim is to apply a custom theme, which contains a beamerthemeTHEMENAME.sty (with sub files beamercolorthemeTHEMENAME.sty, beamerfontthemeTHEMENAME.sty, beamerinnerthemeTHEMENAME.sty, beamerouterthemeTHEMENAME.sty), as a template.tex and Includes.
Currently I source these files in the YAML-header as follows:
theme: "THEMENAME"
template: template.tex
includes:
in_header: preamble.tex
before_body: before_body.tex
after_body: after_body.tex
To organize the presentation and its files more neatly, I would like to move these files ...
to a subfolder of the presentation directory (short-run solution)
to a general folder such the templates can likewise be sourced by/applied to other presentations (long-term solution).
How would I have to adjust the YAML header in each case to correctly source the above-mentioned files?
Meanwhile, I found an answer which works for the short run.
(For hints regarding a long-term solution, see the answer from #Steven and comments by #Samcarter_is_at_topanswers.xyz.)
Drop all files of the custom theme THEMENAME as well as any includes (e.g., preamble.tex) into a subfolder termed beamer_files within the folder in which the Rmd file of the presentation is located in.
Modify the YAML header and beamerthemeTHEMENAME.sty as shown below.
As per these SO answers (LaTex theme, colon), some LaTex hacks are necessary to apply the LaTex beamer theme smoothly in the rmarkdown::beamer_presentation.
MWE.Rmd
---
# COMMENT out "title" in YAML header: else markdown generates a second title page
# ==> if title contains no special characters: feed it straight into LaTex at the end of the YAML header
# ==> if title contains special characters, like ":", feed it in "preamble.tex" sourced in "LaTex Hacks"
subtitle: "Beamer presentation with R-markdown"
institute: "some place"
date: "`r format(Sys.time(), '%B %d, %Y')`"
output:
# beamer_presentation: default
bookdown::pdf_book:
base_format: rmarkdown::beamer_presentation
# Source below in "LaTex Hacks", if want theme to be stored in subfolder (else rmarkdown does not find it)
# theme: "THEMENAME"
# Source "includes" below in "LaTex Hacks" if using custom theme with custom title page
# => else, markdown places the includes at inadequate position in LaTex file, which then either does not show the title or throws an error
# includes: ...
latex_engine: xelatex
toc: false
slide_level: 2
classoption: aspectratio=169 # fix aspect ratio of presentation (169 => 16:9, 149 => 14:9, default: 4:3)
#
# LaTex Hacks
# --------------------------
compact-title: false # to remove markdown generated title frame
header-includes:
# - \title{Title if no special characters}
- \input{beamer_files/beamerthemeTHEMENAME.sty}
- \input{beamer_files/preamble} # feed title to LaTex in preamble.tex due to ":"
- \def\titlefigure{img/my_bg}
- \AtBeginDocument{\titleframe} # add title frame defined in beamerouterthemeTHEMENAME
- \makeatletter\beamer#ignorenonframefalse\makeatother
---
​```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
​```
<!-- TOC - Table of Contents -->
<!-- ======================================================== -->
``` {=latex}
\end{frame}
\tocframe
\begin{frame}
```
## Slide with Bullets
<!-- ======================================================== -->
- Bullet 1
- Bullet 2
- Bullet 3
<!-- Appendix -->
<!-- ======================================================== -->
``` {=latex}
\end{frame}
\appendix
\begin{frame}
```
beamerthemeTHEMENAME.sty
% WAS:
% \usecolortheme{THEMENAME}
% \useoutertheme{THEMENAME}
% NOW:
\input{beamer_files/beamercolorthemeTHEMENAME.sty}
\input{beamer_files/beamerouterthemeTHEMENAME.sty}
\mode<all>
preamble.tex
% "title" is commented out in YAML header: else markdown generates a second title page
% if title contains no special characters: feed it straight into LaTex at the end of the YAML header
% if title contains special characters, like ":" or a forced linebreak feed it to LaTex here:
\title[short version]{First line of the title:\par second line of the title}

Table of contents blank

I am trying to create a beamer presentation using R Markdown. Everything was fine until I updated the software to latest versions of R and RStudio. Now my Table of Contents do not appear (blank page instead) and the words "Section 1", "Section 2" ... etc appear above every Section title on my presentation.
I tried with toc: true, toc: false, changing theme, even creating a new R Markdown beamer from scratch but nothing worked.
---
title: "TITLE"
subtitle: "Subtitle"
author: "Guillermo Ortiz"
date: "9-oct-2019"
output: beamer_presentation
theme: "Madrid"
toc: TRUE
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
# Hello
## Goodbye
Bla bla bla bla
I don't see all of what you describe: I get the section numbers showing, but the table of contents isn't blank. The following fixes the section number issue, but it might not fix your TOC:
The problem is in the generated .tex file. When you specify the theme to be "Madrid", R Markdown is putting the LaTeX line
\usetheme[]{Madrid}
into the .tex file. The problem is that it gets put in after a bunch of customizations to the style (\setbeamertemplate{section page}, etc.) and it overrides them.
[Edited to add:] this is actually how it should be. You asked for Madrid, if you want something different, you should have to ask for it. Pandoc shouldn't be overriding the theme you asked for.
There are several ways to ask for this change to the Madrid theme. One is
to include the request in the header, by putting them in a file (e.g. mysections.sty) and putting this in your YAML:
output:
beamer_presentation:
includes:
in_header: mysections.sty
The mysections.sty should contain something like this (the Pandoc default):
\setbeamertemplate{section page}{
\centering
\begin{beamercolorbox}[sep=12pt,center]{part title}
\usebeamerfont{section title}\insertsection\par
\end{beamercolorbox}
}
You might want other options (e.g. \begin{beamercolorbox}[sep=12pt,center,rounded,shadowed]).

add image in title page of rmarkdown pdf

I am attempting to create an rmarkdown document. I have finally figured out a way to approach this, although it has taken quite some time. The last thing I would like to be able to do is to add an image to the title page of my pdf document.
The trouble I have is that my title page is defined by the top section of YAML. Below is the contents of my example.Rmd file. I use the Knit PDF button in RStudio to turn it into a PDF.
---
title: "This is a my document"
author: "Prepared by: Dan Wilson"
date: '`r paste("Date:",Sys.Date())`'
mainfont: Roboto Light
fontsize: 12pt
documentclass: report
output:
pdf_document:
latex_engine: xelatex
highlight: tango
---
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
summary(cars)
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
If anyone has some tips that would allow me to put an image (logo.png) above my title that would be great.
Based on the previous solution, the following code does not require an auxiliary header.tex file. All contents are contained in the .Rmd file. The LaTeX commands are instead defined in a header-includes block in the YAML header. More info can be found here.
Replace my_graphic.png below with your local graphic file.
---
title: "A title page image should be above me"
header-includes:
- \usepackage{titling}
- \pretitle{\begin{center}\LARGE\includegraphics[width=12cm]{my_graphic.png}\\[\bigskipamount]}
- \posttitle{\end{center}}
output:
pdf_document:
toc: true
---
\newpage
# Section 1
Some text.
I was able to solve this using LaTeX package titling
---
title: "Untitled"
author: "Name"
date: "September 19, 2015"
output:
pdf_document:
includes:
in_header: header.tex
---
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
summary(cars)
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Where the header.tex should include the following code:
\usepackage{titling}
\pretitle{%
\begin{center}
\LARGE
\includegraphics[width=4cm,height=6cm]{logo.png}\\[\bigskipamount]
}
\posttitle{\end{center}}
and replace logo.png with the image you would like to use and make sure the file is in the root directory of your Rmd file. You can change image width and height to your needs. For more information on available options go to titling
For a beamer presentation you can do it like this:
title: "Title"
subtitle: "Subtitle"
author: "author"
date: "date"
header-includes:
- \titlegraphic{\centering \includegraphics[width=12cm]{titlepic.png}}
output:
beamer_presentation:
latex_engine: xelatex
theme: "metropolis"
highlight: "espresso"
classoption: "aspectratio=169"
The titlegraphic will be placed below your title text
For beamer presentation if you want an image at the bottom you can kind of cheat and add the image where the date line should be. Then if you want to insert date you can add institution (which is before date). the ![] should be tabbed (4 spaces from the far left of the page)
date: |
![](mypathtofile/myimage.png){width=3in}

How to add table of contents in Rmarkdown?

I am using RStudio for writing markdown documents and want to add Table of Contents (TOC) at top of the documents so that the user could click the relevant section for reading. There were some relevant examples on rpubs but now I can't seem to find them. Please note that I don't use pandoc and am quite new to Rmd & knitr. Is there any way to add TOCs without using pandoc? If using pandoc is must then which functions are relevant?
EDIT
Here's a small sample page:
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
---
Header 1
---------------
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
## Header 2
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
summary(cars)
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
### Header 3
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
I tried running this in RStudio v 0.98.864 and it worked! but sadly it didn't work on 0.98.501 and 0.98.507. I am working on my thesis in 0.98.501 and after updating RStudio, some of my analyses didn't work. So, I reverted back to 0.98.501.
What should I do now? I really want TOCs but without harming the outputs of other analyses.
The syntax is
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
---
in the documentation. Make sure this is at the beginning of your document. Also make sure your document actually has headers otherwise R can't tell what you want in the table of contents.
Syntax with more options:
---
title: "Planets"
author: "Manoj Kumar"
date: "`r format(Sys.time(), '%B %d, %Y')`"
output:
html_document:
toc: true # table of content true
toc_depth: 3 # upto three depths of headings (specified by #, ## and ###)
number_sections: true ## if you want number sections at each table header
theme: united # many options for theme, this one is my favorite.
highlight: tango # specifies the syntax highlighting style
css: my.css # you can add your custom css, should be in same folder
---
If you are using pdf_document, you might want to add table of contents in a new page, which toc: true does not allow. It puts the table of contents right after the document title, author and date--because it is in yaml.
If you want to have it in a new page, you have to use some latex language. Here is what I did.
---
title: \vspace{3.5in}"Title"
author: "Name"
date: "`r Sys.Date()`"
output:
pdf_document:
fig_caption: true
number_sections: true
---
\newpage # adds new page after title
\tableofcontents # adds table of contents
\listoffigures
\listoftables
\newpage
So, after yaml (the chunk between ---), I added a new page using \newpage, then a table of contents using \tableofcontents, a list of figures using \listoffigures, a list of tables \listoftables, and a new page before everything else.
Note, \vspace{3in} in the title adds vertical space of 3 inch from the top before printing yaml (title, etc.).
Read more here: https://www.sharelatex.com/learn/Table_of_contents

Resources