April 9, 2013

Changing figure options mid-chunk (in a loop) using the pander package.

I wrote already about changing figure options mid-chunk in reproducible research. This can be important e.g. if you are looping through a dataset to produce a graphic for each variable but the figure width or height need to depend on properties of the variables, e.g. if you are producing histograms and want the figures to be a bit wider when there are more bins.

That previous post was about knitr, but at the moment I am using the pander package more than knitr because it makes some things simpler. Changing figure options is a case in point.

Here is the output:

Varying widths for graphs in a loop using the pander package

Results for: mpg

loop-734
Anything you type here will be inside the same paragraph as the figure and so works like a pseudocaption

Results for: cyl

loop-735
Anything you type here will be inside the same paragraph as the figure and so works like a pseudocaption

And here is the code:

Varying widths for graphs in a loop using the pander package

\<% for (varn in names(mtcars[,1:2)) { %>\<%=
var=mtcars[,varn]
pandoc.p.return(“”)
pandoc.header.return(paste(“Results for: ,varn,“”),3)
pandoc.p.return(“”)
fac=(100*log(length(unique(var))))#calculate some factor to ensure somewhat wider graphs for more bins

%>\<% evals.option(“width”,50+fac) %>\<%= #have to break out of the BRCODES to change the height options for the next chunk
qplot(var,geom=“bar”)+xlab(varn)%>
\Anything you type here will be inside the same paragraph as the figure and so works like a pseudocaption\<%
# coord_flip()
%>\<% } %>

Oh, and to make it all happen:

library(pander)

library(ggplot)

Pandoc.brew(convert=“html”,output=“loop”,“nameOfFileContainingTheAboveScript.R”)


R reproducibleResearch code


Previous 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...
Next post
Building a custom database of country time-series data using Quandl Encouraged by this post I had another look at quandl for collecting datasets from different agencies. Right now I need to get data for four...


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