knitr: Changing chunk options like fig.height programmatically, mid-chunk

February 22, 2013
By

(This article was first published on socialdatablog » R, and kindly contributed to R-bloggers)

Knitr is a great tool for doing reproducible research.
You can produce all kinds of output inside a single knitr chunk, e.g. you can write a loop to produce lots of figures or tables. The only catch is if you want your figures to have differing captions, heights, etc (and usually you do). The standard way is to write a separate chunk for each figure and set the options in the chunk header. So you can’t produce several differing figures from inside one chunk.
Or can you?

This works for me, based on hints from Yui on github.


\documentclass{article}

\begin{document}
<<>>=
opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA, warning=FALSE,message=FALSE,fig.width=6, echo=F)
kexpand=function(fh,cap){
cat(knit(
text=knit_expand(text=
"<<{{cap}},fig.height={{fh}},fig.cap={{'cap'}}>>=\n
.q\n
@"
)
))}
@

<>=
library(ggplot2)
.q=qplot(1:10)
kexpand(2,"one")
.q=qplot(1:20)
kexpand(8,"two")

@
\end{document}

Warning: wordpress is eating some of my <<>>. Make sure your chunks are formed with the usual chunk syntax.

So one key thing is to set progress and verbose to F otherwise they destroy the output. Then the little function kexpand expands an inline template which is typed as text as part of the function. Then you can define your plot as .q and your caption as cap, and your heights etc. You could adapt the function to control other options. Strangely, .q doesn’t have to be an argument for the function, you can just set it in the current environment and it gets picked up by the function anyway. Don’t know if this is good practice or why it works but it does.

I just posted this same trick in response to a question on stackoverflow. Let’s see if it gets accepted.

Update: added argument for figure height.

To leave a comment for the author, please follow the link and comment on his blog: socialdatablog » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.