February 22, 2013

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

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=
<<,fig.height=,fig.cap=>>=\n
.q\n
@“
)
))}
@

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

@
\end{document}

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.


R reproducibleResearch code


Previous post
Rstudio, not vim, for reports I just wasted a dozen hours scattered over several days testing out vim instead of r-studio for when I am writing longer reports with a lot of text...
Next post
Haiti: Request for Qualifications for research teams to conduct an impact evaluation of the Integrated Neighborhood Approach (INA) Very proud and happy to see that this idea, which we developed while I was in Haiti with the IFRC, is nearing fruition:3ie will be issuing a Request...


This blog by Steve Powell is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License and powered by Blot.
Privacy Policy
.