简体   繁体   中英

Chunk reference using knitr, r markdown and pandoc (pander)

I am having trouble trying to reference chunks within ar markdown document which I am trying to convert to .pdf using pandoc.convert.

If I include \\label{mylabel} within the text - I can reference this by \\ref{mylabel} . However, I thought I might be able to refer to a chunk (or table / figure within a chunk) similarly - but am having no luck.

For instance, for the chunk:

```{r myplot, echo=FALSE, warning=FALSE}
plot(cars)
```

I though I might be able to put \\ref{myplot} or \\ref{fig:myplot} or even an internal markdown reference [car plot](myplot) . The documentation seems to mention that labels are created based on the name of the chunk and these are the formats suggested in relation to similar questions. But none seem to work.

Similarly for tables (which I create using pander) - I have chunks like:

```{r car_sum}
library(pander)
car_summary<-summary(cars)
pander(car_summary, caption = "This is a summary of cars")
```

When converting to .pdf from the .md file using 'pandoc.convert' the tables are given a nice title 'Table 3 This is a summary of cars' and are numbered but I cannot seem to use the label as a reference \\ref{car_sum} and it always shows as '??'. Some forums seem to mention that you have to include 'tab:' or 'fig:' before the label name but this still does not work for me.

Can chunk referencing within text be done? If so, what needs to be typed to do this correctly so it works in the final document showing something like 'see Table 2'.

Anything is possible!!

Please see this gist which does what you describe. Just save and knit it to see it in action... For some reason Rpub didn't want to publish it (unknown error).

Testing with converting the knitr generated .html to .pdf via pandoc resulted in working links as well, which is a nice bonus!

The workhorse is::

```{r setup, echo=FALSE, results='hide'}
chunkref <- local({
  function(chunklabel) {
    sprintf('[%s](#%s)', chunklabel, chunklabel )
  }  
})

secref <- local({
  function(seclabel) {
    sprintf('[%s](#%s)', seclabel, seclabel )
  }  
})

pgref <- local({
  function(n)
  sprintf('[Page-%i](#Page-%i)', n, n)
})

sec <- local({
  function(seclabel) {
    sprintf('# <a name="%s"/> %s', seclabel, seclabel )
  }  
})

pgcount <- local({
  pg <- 0
  function(inc=T) {
    if( inc ) { pg <<- pg + 1 }
    return( pg )
  }
})

pganchor <- local({
  function(doLabel=T) {
    if( doLabel) {
      sprintf('\n-----\nPage-%i\n<a name="Page-%i"/>\n', pgcount(inc=F), pgcount() )
    } else {
      sprintf('\n<a name="Page-%i"/>\n', pgcount() )
    }
  }
})

knit_hooks$set( anchor = function(before, options, envir) {
  if ( before ) {
    sprintf('<a name="%s"/>\n', options$label )
  }
})

knit_hooks$set( echo.label = function(before, options, envir) {
  if ( before ) {
    sprintf('> %s', options$label )
  }
})

knit_hooks$set( pgbreak = function(before, options, envir) {
  if ( !before ) {
    pganchor();
  }
})
````

Which allows for multiple types of references to be created...

Inline: `r sec("Introduction")` then `r secref("Introduction")`

Or

As chunk options:

```{r car-summary, echo=T, warning=FALSE, anchor=T, pgbreak=T, echo.label=F}`

then

`r chunkref("car-summary")`

Even 'top of page' links and 'bottom of page' markers and labels...

Easier solution to referring to figures: put this in the fig.cap field (double \\\\ to escape the first \\ ):

fig.cap="\\label{mylabel}Caption of my figure."

Then, use \\autoref{mylabel} to refer to the figure in the main text.

I am using RStudio with Rmarkdown. Full RMD document:

---
output: pdf_document
---

```{r fig.cap="\\label{mylabel}Caption of my figure."}
plot(1)
```

The generated figure is \autoref{mylabel}.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM