R – How to add table of contents in Rmarkdown

rr-markdownrstudio

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.

Best Answer

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.

Related Topic