How to Set and Change Heading Levels in R Markdown

Learn how R Markdown headings work, how to write them correctly, and how to shift heading levels safely without changing code chunks, YAML or other content.

Headings in an R Markdown (.Rmd) file give a report its structure. They control how sections are nested, what appears in a table of contents, how sections are numbered, and in HTML output, how tabbed sections are grouped. This guide covers how to write a header in R Markdown, how heading levels affect the rendered document, and how to change those levels later without touching code or other content. The behavior described follows the general documented conventions of R Markdown and Pandoc, the conversion tool R Markdown uses behind the scenes. No version-specific evidence was supplied for this guide, so confirm option names against the rmarkdown and Pandoc versions you have installed.

What heading markup does to your text

Heading markup takes a plain line of text in the Markdown body of an .Rmd file and turns it into a section heading in the output, such as an h1 to h6 element in HTML or a section command in LaTeX/PDF. The level you choose determines nesting: a level-3 heading belongs to the nearest level-2 heading above it. That structure is then used by features such as the table of contents, section numbering and tabsets. Heading markup only applies to Markdown text. It does not apply inside R code chunks or the YAML front matter at the top of the file.

Writing headings: the basic syntax

The most common form is the ATX heading. Start a line with one to six hash signs (#), followed by a space and the heading text. The number of hash signs sets the level. The following is an illustrative example:

# Level 1 heading

## Level 2 heading

### Level 3 heading

#### Level 4 heading

##### Level 5 heading

###### Level 6 heading

Two details are easy to miss. First, Pandoc's Markdown requires a space between the hash signs and the text, so #Results without a space is treated as an ordinary paragraph rather than a heading. Second, Pandoc expects a blank line before a heading. If a heading line comes immediately after a paragraph line with no empty line between them, it may be read as part of that paragraph. Both rules involve whitespace you cannot easily see, so check those first when a heading fails to render.

Pandoc also supports setext headings for levels 1 and 2. In this form, the text is underlined with equals signs for level 1 or hyphens for level 2. This style cannot express levels 3 to 6, and a line of hyphens can be confused with other syntax, so ATX headings are usually the clearer choice in R Markdown. Illustrative example:

Level 1 heading
===============

Level 2 heading
---------------

Headings versus the document title

The title field in the YAML front matter is rendered as the document title. It is not part of the body headings. Because the title already sits at the top of the page, many authors start body sections at level 2 (##) so the title stays visually and structurally above them. This is a convention rather than a requirement. Pick one starting level and use it consistently, since mixed starting levels make the table of contents and numbering harder to read. Illustrative example:

---
title: "Quarterly Report"
output: html_document
---

## Summary

## Methods

### Data sources

Hash signs inside code chunks are not headings

Inside an R code chunk, a line beginning with # is an R comment. It is not a Markdown heading. In the illustrative example below, only the first line becomes a heading. The comment inside the chunk is displayed as code.

## Model fit

```{r}
# Fit a linear model
fit <- lm(mpg ~ wt, data = mtcars)
```

This distinction matters when you change heading levels by search and replace. A pattern that matches every line starting with # will also rewrite R comments, and YAML comments too. The section on shifting levels below covers how to avoid this.

Controlling what heading levels do in the output

Several output options in the YAML header respond to heading levels. The following illustrative html_document configuration turns on a table of contents, limits it to a chosen depth and numbers the sections:

---
title: "Quarterly Report"
output:
  html_document:
    toc: true
    toc_depth: 3
    number_sections: true
---
  • toc: true adds a table of contents built from your headings.
  • toc_depth sets the deepest heading level included in the table of contents. Setting it explicitly is clearer than relying on the default.
  • number_sections: true numbers headings according to their nesting, so skipping a level, for example going from # straight to ###, can produce numbering that looks odd.
  • The exact options available depend on the output format, so check the documentation for the format you use (for example, html_document or pdf_document).

Heading attributes: IDs, unnumbered sections and tabsets

Pandoc lets you add attributes in curly braces at the end of a heading line. Attributes change how a heading behaves without changing its level. Illustrative examples:

## Introduction {#intro}

## Appendix {-}

## Appendix {.unnumbered}

## Results {.tabset}

### Table

### Plot
  • {#intro} gives the heading a fixed identifier, which keeps internal cross-references stable if you later reword the heading.
  • {-} and {.unnumbered} exclude a heading from section numbering when number_sections is on.
  • {.tabset} on a heading in html_document output turns the headings one level below it into tabs. This depends on the levels, so if you shift the parent heading, shift its child headings by the same amount or the tabs will break.

Changing heading levels: two approaches

There are two ways to change heading levels. You can shift them only in the rendered output and leave the .Rmd source unchanged, or you can rewrite the source text itself. The first is safer when you only need a different structure in the result. For example, you might demote everything by one level because the YAML title already acts as the top level. The second suits a permanent restructure.

Option 1: shift levels at render time with Pandoc

Pandoc has a --shift-heading-level-by option. A positive number demotes headings: with a value of 1, # becomes level 2 and ## becomes level 3. A negative number promotes them. You can pass it through pandoc_args in the YAML header. Illustrative example:

---
title: "Quarterly Report"
output:
  html_document:
    pandoc_args: ["--shift-heading-level-by=1"]
---

Older Pandoc releases used a different option, --base-header-level. Run pandoc --help, or check the Pandoc version used by your R setup, to confirm which option is available. According to Pandoc's documentation, a heading cannot go below level 1. With a negative shift, a heading that would end up below level 1 is turned into an ordinary paragraph. The exception is a heading at the very start of the document, which can become the document title instead. After using a negative shift, inspect the output to confirm nothing was flattened into body text.

Option 2: rewrite the source text safely

To change the .Rmd file itself, avoid a single search-and-replace across the whole file. A safe edit changes only Markdown heading lines. It skips the YAML front matter, which can contain comments starting with #, and it skips fenced code chunks, where # starts R comments. The illustrative R script below adds one hash sign to headings of levels 1 to 5, skips both of those regions, and writes the result to a new file so the original stays unchanged. It is an example only and has not been tested against your files.

lines <- readLines("report.Rmd")
in_yaml <- length(lines) > 0 && grepl("^---[[:space:]]*$", lines[1])
in_chunk <- FALSE

for (i in seq_along(lines)) {
  if (in_yaml) {
    if (i > 1 && grepl("^(---|[.][.][.])[[:space:]]*$", lines[i])) in_yaml <- FALSE
    next
  }
  if (grepl("^[[:space:]]*```", lines[i])) {
    in_chunk <- !in_chunk
    next
  }
  if (!in_chunk && grepl("^#{1,5} ", lines[i])) {
    lines[i] <- paste0("#", lines[i])
  }
}

writeLines(lines, "report-shifted.Rmd")
  • The pattern ^#{1,5} followed by a space matches only lines that start with one to five hash signs and a space. That is the heading form described earlier.
  • Level-6 headings are not changed, because Markdown has no level 7. Restructure those by hand.
  • The chunk check assumes code chunks use triple-backtick fences. Chunks fenced with tildes or longer backtick runs need a matching adjustment.
  • To promote headings instead, remove one leading hash from lines that match ^#{2,6} followed by a space, and decide separately what to do with existing level-1 headings.

Verifying the result

  • Compare the original and edited files with a diff tool. Only heading lines should differ, and each should differ by a single hash sign.
  • Confirm that no line inside a code chunk or the YAML header changed.
  • Knit the document and check the table of contents, section numbering and any tabsets against the structure you intended.
  • If a heading appears as plain text, check for a missing space after the hash signs or a missing blank line before the heading.

Gaps in this guide

No version numbers, default values or test results were supplied for this guide. The syntax rules and options above reflect generally documented R Markdown and Pandoc behavior, but defaults and option names can differ between releases and output formats. Treat the code samples as illustrations and verify them on a copy of your own document.