Skip to content Skip to sidebar Skip to footer

Use Internal Links In RMarkdown HTML Output

I am using R Studio to create a markdown document. I tried: Jump to [Header 1](#anchor) I would like to set up a link so when a reader clicks it, can jump to a specific point on

Solution 1:

Pandoc supports explicit and implicit section references for headers; see the pandoc manual.

  • explicit: you give a custom name to a header ## Test {#test} and later refer to it with a link syntax: see [the relevant section](#test).
  • implicit: headers where you don't set a custom name, like ## Test, can still be refered to: See the section called [Test].

Both syntax should allow you to click on the link to go to the anchor, and should work in most output format. (only tested with html and pdf).

---
output:  pdf_document
---

## A section

blah blah

## A second section with a custom identifier {#custom}

blah blah

## Links

You can use implicit references to refer to sections
you have not explicitly named, like this: 
see [A section]. 

You can use links to refere to sections with explicit
references, like this: see [the second section](#custom).

Solution 2:

Here is a solution for HTML documents using jQuery:

---
title: "Internal Links"
output: html_document
---

# First Section

## Second Section

### Third Section


<script type="text/javascript">
  // When the document is fully rendered...
  $(document).ready(function() {
    // ...select all header elements...
    $('h1, h2, h3, h4, h5').each(function() {
      // ...and add an id to them corresponding to their 'titles'
      $(this).attr('id', $(this).html());
    });
  });
</script>


<a href="#First Section">Go to first section</a><br>
<a href="#Second Section">Go to second section</a><br>
<a href="#Third Section">Go to third section</a>

As the comments point out, we simply select all headers, read out their content (e.g. "First Section") and add the attribute id with the value corresponding to the specific content to each header. Now you can link to any header using #HEADER (e.g. #First Section).


This is of course extendable to all other elements you wish to put an anchor on. So if you want to link to any of your chunks, simply add this script to your document:

<script type="text/javascript">
  $(document).ready(function() {
    $('pre.r').each(function(i) {
      $(this).attr('id', 'Chunk_' + i);
    });
  });
</script>

Now you can link to the chunks by using <a href="Chunk_i">My Chunk</a> where i goes from 0, the first chunk, to N, the very last chunk in your document.


Post a Comment for "Use Internal Links In RMarkdown HTML Output"