Is it possible to add labels and references to knitr output other than figures and tables.
I know I can use xtable
respectively print.xtable
to set captions for tables and place them like I would like to. A similar thing can be done to figures. But is it possible to label and caption some output that was generated
simply by echoing some R code? So that I could write something like this in my text: code chunk \ref{mychunk} shows how to do XYZ
.

- 27,631
- 38
- 141
- 207
3 Answers
Yes it is possible. See example 074 on how to define an environment for R chunks so that you can make use of cross references. To completely understand it, you may need to read the documentation of chunk hooks.

- 28,913
- 23
- 193
- 419
-
1Thx for helping out for the second time within the last 24 hrs. For me it might be the other way around: read too much documentation and less examples. Just learned they existed despite using knitr and several of its advanced options for a while. Maybe you should link from the demos to the examples on github. However, others maybe better finding them, thx man! – Matt Bannert Jan 16 '13 at 08:44
-
I have been working on a knitr book (which discussed this feature in detail), so there was lower priority on the website. You are absolutely right that I should have a link in the demo page, although I already have one in the homepage. – Yihui Xie Jan 16 '13 at 17:10
-
2a knitr book! that's absolutely awesome. That's most definitely the right excuse for that missing link. I will tell everybody and their grandmothers when that book is out. – Matt Bannert Jan 17 '13 at 08:41
I wanted additional text in the caption after the head, so used this in the preamble for customizing my code chunk captions using amsthm:
\usepackage{amsthm}
\newtheoremstyle{rexample}
{3pt}%Space above
{3pt}% Space below
{}%Body font
{}%Indent amount
{\bfseries}%Theorem head font
{:}%Punctuation after theorem head
{.5em}%Space after theorem head
{}%Theorem head spec (can be left empty, meaning `normal')
\theoremstyle{rexample}
\newtheorem{rexample}{Code chunk}
Following the example, I used knit_hooks with options$comment:
knit_hooks$set(rexample = function(before, options, envir) {
if (before) sprintf('\\begin{rexample}%s\\label{%s}\\hfill{}', options$comment, options$label) else '\\end{rexample}'
})
And in the chunk definition, the comment is passed to form the label:
<<setup, echo=TRUE, tidy=FALSE, eval=FALSE, rexample=TRUE, comment='Setups for some management functions and database connections'>>=
Which gives me a nice caption:
http://gis.washington.edu/phurvitz/knitr/rexample_theorem_caption.png

- 41
- 1
Not sure if this is exactly what you are looking for but try and give this site a shot:
http://yihui.name/knitr/demo/reference/
Don't be irritated by the first sentence talking about Sweave chunks, it's totally focused on knitr chunks.
Cheers ...

- 1,387
- 10
- 22