[R] odfWeave - A loop of the "same" data

Charles C. Berry ccberry at ucsd.edu
Thu Jun 1 18:35:38 CEST 2017


> Before I go and do this another way - can I check if anyone has a way of 
> looping through data in odfWeave (or possibly sweave) to do a repeating 
> analysis on subsets of data?
> For simplicity lets use mtcars dataset in R to explain.  Dataset looks like this:
>> mtcars
>               mpg cyl disp  hp drat   wt ...
> Mazda RX4     21.0   6  160 110 3.90 2.62 ...
> Mazda RX4 Wag 21.0   6  160 110 3.90 2.88 ...
> Datsun 710    22.8   4  108  93 3.85 2.32 ...
>               ............
> Say I wanted to have a 'catalogue' style report from mtcars, where on 
> each page I would perhaps have the Rowname as a heading and then plot a 
> graph of mpg highlighting that specific car
> Then add a page break and *do the same for the next car*.  I can manually do this of course, but it is effectively a loop something like this:
> for (n in length(mtcars$mpg)) {
> barplot (mtcars$mpg, col=c(rep(1,n-1),2,rep(1,length(mtcars$mpg)-n)))
> }
> There is a odfWeave page break function so I can do that sort of thing 
> (I think).  But I don't think I can output more than one image can I? 
> In reality I will want several images and a table per "catalogue" page.
> At the moment I think I need to create a master odt document, and create 
> individual catalogue pages.  And merge them into one document - but that 
> feels clunky (unless I can script the merge!)
> Anyone got a better way?

For a complex template inside a loop, I'd probably do as Jeff suggests and 
use a knitr child document for ease of developing and debugging the 

But for the simple case you describe I'd use a brew script to
unroll the loop.

You would write your input file as usual, but put a brew script in the
right place, then run brew on the input file to produce an
intermediate file that unrolls the loop, then weave the intermediate
file to get your desired result.  Here is a simple example of such you 
can run in an R session (assuming the brew package is installed) and see 
the results printed out.

--8<---------------cut here---------------start------------->8---


Everything before the loop

<% for (i in 1:10) { %>
Print the value of i
<% print(i) %> or better yet
\\Sexpr{<%= i %>}
<% } %>

everything after


--8<---------------cut here---------------end--------------->8---

The double backslash is needed in the literal string used here.  If
you put that script in a file using an editor, you would just use a
single backslash.



More information about the R-help mailing list