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
.
Code chunks in an R Markdown document contain your R code. All code chunks start and end with ``` – three backticks or graves.
Rendering Output There are two ways to render an R Markdown document into its final output format. If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it.
If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .
Chunk Options include = FALSE prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks. echo = FALSE prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.
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.
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
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With