How to Change the Position of the Table of Contents in Rmarkdown

How to change the position of the table of contents in rmarkdown?

The position of the TOC is fixed in the R Markdown default HTML template. If you want to change its position in the document, you'll need to modify the template:

  1. Make a copy of the R Markdown HTML template to use as a starting point. You can find it by running this R command: system.file("rmd/h/default.html", package="rmarkdown")
  2. Move the $toc section to where you want the table of contents to appear.
  3. Save the modified template in the same folder as the document you're rendering as e.g. lowertitle.html
  4. Add template: lowertitle.html to the html_document settings.

From the standpoint of the template, all of the document's content is an atomic unit, so it might be necessary to put any content you want to appear before the TOC in the template itself.

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

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).

  1. 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.

  2. 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
  3. 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)

Output page 1
Output page 2
Output page 3

Add Table of contents in different position in Rmd pdf

Using the code you provided I'm able to knit the pdf document and get the three plots, one for each Species in iris.

This code, however, produces two TOCs: one of them in the first page which is not desired according to your question. In order to get only the TOC produced by the function render_toc() set toc: no in the YAML header.

---
title: "test"
output:
pdf_document:
number_sections: yes
toc: no
toc_depth: 4
---

This way only one TOC will be generated and placed where render_toc() is.


Edit: After seeing your edit with the desired output, I think the following LaTeX code can help:

\newpage
\thispagestyle{plain}
\mbox{}

\setcounter{tocdepth}{2}
\renewcommand{\contentsname}{Table of Contents}
\tableofcontents

\newpage
\thispagestyle{plain}
\mbox{}

Note: here we are not using render_toc(). The code creates the TOC in the second page of the document. If you need another blank page, just introduce another block of:

\newpage
\thispagestyle{plain}
\mbox{}

These pages may or may not be numbered, which you control via the argument passed to \thispagestyle{}. See here for more details.

Full code:

---
title: "Document title"
output:
pdf_document:
number_sections: yes
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\newpage
\thispagestyle{plain}
\mbox{}

\setcounter{tocdepth}{2}
\renewcommand{\contentsname}{Table of Contents}
\tableofcontents

\newpage
\thispagestyle{plain}
\mbox{}

# Test 1
## Subsection 1

# Test 2
## Subsection 2

# Test 3

```{r, results='asis', echo=FALSE}
library(ggplot2)
for(Species in levels(iris$Species)){
cat('\n#', Species, '\n')
p <- ggplot(iris[iris$Species == Species,],
aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
print(p)
cat("\n")
}
```

This way we end up with a TOC looking like this:

Sample Image

Rmarkdown setting the position of kable

You can replace "hold_position" from claudius answer with "HOLD_position":

```{r}    
kable(cars %>% filter(cars$speed>=23), caption = "Speed vs distance") %>%
kable_styling(latex_options = "HOLD_position")
```

As mentionned in the kableExtra package:

if you find hold_position is not powerful enough to literally PIN your table in the exact position, you may want to use HOLD_position, which is a more powerful version of this feature. For those who are familiar with TeX, hold_position uses[!h] and HOLD_position uses [H] and the float package.

ref: https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

You may also want to control figure position by adding fig.pos='H' to the figure chunk header.

How to add table of contents in Rmarkdown?

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.

Position of Table of Contents in R Bookdown

@broti working from what was given in the comments, I went ahead and implemented this with a quick lorem ipsum example. Hopefully that works for you.

---
title: "Title"
subtitle: "Subtitle"
author:
- "Institution"
- "Name"
date: "September 2020"
output:
bookdown::pdf_book:
toc: false
toc_depth: 2
abstract: |
The text of your abstract. 150 -- 250 words.
keywords:
- key
- dictionary
- word
fontsize: 12pt
linestretch: 1.5
toc-depth: 2
secnumdepth: 2
lof: True
lot: True
csl: american-political-science-association.csl
geometry: "left=2.5cm, right=2.5cm, top=2.5cm, bottom=2.5cm"
---

\tableofcontents

\newpage

# Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis malesuada nulla eget nisi viverra, ac sodales metus euismod. Fusce at augue augue. Ut pretium mauris egestas metus vulputate interdum. Etiam vitae scelerisque lectus. Nullam augue sapien, lobortis vel interdum id, tempor quis leo. Curabitur dictum tellus sed velit pellentesque, quis eleifend neque congue. Pellentesque id egestas elit. Fusce cursus, elit lobortis semper ornare, nisi sem tempus risus, a pulvinar diam augue id mi. Suspendisse vel dolor sit amet felis pharetra pulvinar.

Phasellus nec consequat nibh. In sagittis urna et libero consequat, consequat elementum magna fringilla. Morbi magna eros, tincidunt eu vestibulum ut, mollis ac nibh. Vestibulum est purus, consectetur vel iaculis ut, finibus nec nibh. Aliquam diam mauris, tincidunt eu eros id, tempus ornare massa. Curabitur laoreet vel velit non pulvinar. Maecenas in posuere dolor, eu auctor lorem.

Aliquam et nisi vitae orci rhoncus varius commodo id nunc. Phasellus sit amet blandit mi. Cras sagittis risus non leo auctor vehicula. Maecenas commodo cursus tellus facilisis varius. Quisque vitae odio ac eros ultricies scelerisque et ut massa. Duis enim nibh, molestie eget risus eget, malesuada condimentum purus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam posuere egestas nisi, in fringilla neque tincidunt et. Mauris vestibulum ut tellus quis sollicitudin. Donec vitae tellus dui. Sed sit amet leo posuere, lobortis felis eu, ornare nisi. Nam mi ligula, viverra ac libero quis, cursus ornare quam. Phasellus ut ex posuere, euismod mi sit amet, convallis turpis. Cras eros lacus, pulvinar eu lacinia dictum, feugiat ac felis.

Aenean molestie at tortor id rutrum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nulla cursus faucibus neque finibus rhoncus. Proin vitae tellus vitae tortor vulputate tempus. Nulla nec tempor elit. Nulla facilisi. Sed vel justo felis. Nullam id malesuada mi. Sed est sem, condimentum et eros vel, cursus bibendum magna. Aliquam convallis odio sed nisi tempus lobortis. Quisque sed augue turpis. Vestibulum faucibus tellus ac ullamcorper efficitur. Donec ultricies velit vel lorem mollis consequat. Cras commodo egestas aliquam. Morbi volutpat commodo lorem, gravida tristique nunc ornare in. Maecenas auctor lorem magna, eu finibus enim vestibulum sodales.

Sed a tincidunt orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Aenean rhoncus dui sit amet metus rhoncus euismod. Etiam risus arcu, porttitor nec velit sed, imperdiet placerat tortor. Pellentesque at erat congue, cursus nisi ac, varius diam. Ut posuere ac massa vel pulvinar. Proin metus neque, blandit id sapien id, eleifend fringilla tellus. Quisque massa tortor, pretium et massa consequat, laoreet convallis mi. Proin pretium turpis ornare elementum iaculis. Suspendisse pulvinar congue diam quis finibus. Donec at eros vehicula, elementum urna at, ultricies est. Phasellus porttitor tincidunt pharetra.

side note: something about the documentclass: book item is not functionally working. Hopefully you can work around that.

In RMarkdown, can a floating TOC be placed on the right side of page

Insert the CSS chunk below (after YAML) and try increasing/decreasing the values of px (right and margin-left) for fine-tuning:

---
title: "some title"
author: "me"
date: "3/2/2020"
output:
html_document:
toc: TRUE
toc_float: TRUE
---

```{css toc-content, echo = FALSE}
#TOC {
right: 270px;
margin: 20px 0px 25px 0px;
}

.main-container {
margin-left: 200px;
}
```

R Position of figures in RMarkdown

Just add latex_options=c("hold_position") inside kable_stylying:

df1 <- tibble(column1= 1:10, column2=11:20)

df1 %>%
kable("latex", booktabs=T, caption = "Dataframe 1") %>%
kable_styling(latex_options = c("hold_position"))


Related Topics



Leave a reply



Submit