Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I am having trouble trying to reference chunks within a r 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'.

like image 285
Jimichanga1 Avatar asked Jun 18 '13 10:06

Jimichanga1


People also ask

Does rmarkdown use Pandoc?

A recent version of Pandoc (>= 1.12. 3) is required to use the rmarkdown package. RStudio also automatically includes this so you do not need to download Pandoc if you plan to use rmarkdown from the RStudio IDE.

What is pander function R?

pander: An R 'Pandoc' WriterContains some functions catching all messages, 'stdout' and other useful information while evaluating R code and other helpers to return user specified text elements (like: header, paragraph, table, image, lists etc.)

What is the function of knitr in creating markdown document?

knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.

What package is pander in in R?

pander is an R package containing helpers to return Pandoc's markdown even automatically from several type of R objects with a general S3 method.


2 Answers

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...

like image 180
Thell Avatar answered Oct 18 '22 02:10

Thell


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}.
like image 38
nickmatzke Avatar answered Oct 18 '22 03:10

nickmatzke