[R] keep track of variables created in each chapter of a knitr book

Rainer Schuermann Rainer.Schuermann at gmx.net
Sat Jan 25 18:38:56 CET 2014


You could initialize one list per chapter,

> x1 <- list( "Chapter One" )

and then crate your variables as list members

> x1$A <- c( 1, 2, 3 )
> x1$B <- "bla"
> x1$tv.data <- data.frame( m = sample( LETTERS, 5 ), 
                            n = round( runif( 5 ), 2 ) )

> x1
[[1]]
[1] "Chapter One"

$A
[1] 1 2 3

$B
[1] "bla"

$tv.data
  n    m
1 T 0.92
2 G 0.77
3 B 0.96
4 W 0.67
5 S 0.16

which you can keep track of easily at any time. You could save each list per chapter, if you wanted to. And you can remove it as easily with a simple 

> rm (x1 )

A bit more typing, but much cleaner, I think.

Rgds,
Rainer





On Friday 24 January 2014 09:14:39 Michael Friendly wrote:
> In a book project using knitr, I'm creating a large number of variable 
> and objects in chunks within
> chapters.  I'd like to find a way of keeping track of all of those for 
> each chapter, and clean up
> at the end of each chapter, without having to manually list their names 
> as shown below.
> 
> The book.Rnw file uses a collection of child documents:
> 
> <<ch1, child='ch01.Rnw'>>=
> @
> 
> <<ch2, child='ch02.Rnw'>>=
> @
> 
> <<ch3, child='ch03.Rnw'>>=
> @
> ...
> 
> A typical chapter file, ch02.Rnw begins with a setup chunk and ends with 
> a cleanup chunk:
> 
> <<setup2, echo=FALSE>>=
> source("Rprofile.R")
> knitrSet("ch02")
> require(vcdExtra, quietly = TRUE, warn.conflicts = FALSE)
> @
> 
> .... content ...
> 
> <<cleanup2,results='hide'>>=
> remove(list=objects(pattern="array|mat|my|\\.tab|\\.df"))
> remove(list=c("A", "B", "age", "count", "ds", "n", "passed", "sex", 
> "tab", "tv.data", "TV2", "TV"))
> ls()
> @
> 
>




More information about the R-help mailing list