user101089
user101089

Reputation: 3992

knitr/pandoc: Cross-references to sections, subsections

[Environment: Win 7, R 3.2.3, RStudio, latest]

I have a knitr .Rmd document to be an article, where I want to label sections, as in

## Mean differences {#sec:meandiff}

and then reference that section so it appears in the text as "In Section 3.2, I discuss ..." I can see that something like this is possible using bookdown, and there is some mention of "Internal links" in the pandoc documentation, http://rmarkdown.rstudio.com/authoring_pandoc_markdown.html#links, but I can't make it work. I recall seeing something on this in RStudio-related docs or blogs, but can't find it now.

I tried various things like

In Section (@#sec:meandiff) ...
In Section (@sec:meandiff) ...
In Section (#sec:meandiff) ...

However, the PDF produced renders this just as

In Section (@#sec:meandiff) ...
In Section (???) ..., with: pandoc-citeproc: reference sec:meandiff not found
In Section (#sec:meandiff) ...

The YAML header I'm using is:

---
title: "My title"
author: Moi Meme
date: '`r format(Sys.time(), "%B %d, %Y")`'
output:
  pdf_document:
    fig_caption: yes
    keep_tex: yes
    number_sections: yes
    includes:
        in_header: mystyles.tex

There aren't so many such cross-references that I can't do them manually, but if I'm missing something about syntax having them done by pandoc would make it easier.

Upvotes: 3

Views: 5082

Answers (2)

tjd
tjd

Reputation: 780

You could use pandoc-secnos, which is part of the pandoc-xnos filter suite. The section

My Title
========

is referenced using @sec:my-title. Alternatively, an id can be explicitly assigned to the header, like

My Title {#sec:title}
========

which is referred to using @sec:title. The filter is applied by adding --filter pandoc-secnos to the pandoc command-line call.

A benefit to this approach is that output in many different formats (LaTeX/pdf, html, epub, docx, ...) is possible.

Upvotes: 3

user101089
user101089

Reputation: 3992

Ah, since I'm generating LaTeX, I can just use it to do the cross-references, while the \labels are generated by markdown / pandoc

In the preamble,

\newcommand*{\secref}[1]{Section~\ref{#1}}

then in the text

In \secref{sec:mean-diff} ...
...

## Mean differences {#sec:meandiff}

Upvotes: 4

Related Questions