Matt Bannert
Matt Bannert

Reputation: 28274

Can I label knitr code chunks and outputs and add captions to them?

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.

Upvotes: 16

Views: 4165

Answers (3)

Philip Hurvitz
Philip Hurvitz

Reputation: 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

Upvotes: 3

Yihui Xie
Yihui Xie

Reputation: 30194

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.

Upvotes: 9

GWD
GWD

Reputation: 1464

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

Upvotes: 2

Related Questions