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