Question

I'm writing a book using a book.Rnw master file to compile the whole thing and a chapter.Rnw file to compile just a single chapter. I have to do this because it takes too long to compile the whole book when I'm working on one chapter, and knitr doesn't support the \includeonly{} facility of LaTeX because it writes all child documents to a single file, rather than separate files than can be \include{}ed.

To keep the page and chapter/section numbers straight in the chapter, I use the following LaTeX in chapter.Rnw, but comment out those lines for other chapters, unless it is the last.

\documentclass[11pt]{book}
...

% Ch 1
\setcounter{chapter}{0} % one less than chapter number
\setcounter{page}{0}    % one less than book page number

% Ch 2
\setcounter{chapter}{1} % one less than chapter number
\setcounter{page}{18}   % one less than book page number
...    

% Ch 7
\setcounter{chapter}{6} % one less than chapter number
\setcounter{page}{236}  % one less than book page number

followed by a child chunk for the current chapter:

\begin{document}
<<ch7, child='ch07.Rnw'>>=
@
...
\end{document}

I'd like to parametrize the \setcounter{} calls with a chunk. Here is what I tried, before the \begin{document} but it doesn't work, probably because I don't quite know how to mix R and Latex output in a chunk:

<<set-counters, results='asis', tidy=FALSE, echo=FALSE>>=
.pages <- c(1, 19, 51, 101, 145, 201, 237)
.chapter <- 7
\setcounter{chapter}{.chapter-1}       % one less than chapter number
\setcounter{page}{.pages[.chapter]-1}  % one less than book page number
@

I am getting the following error:

> knit2pdf("chapter.Rnw", quiet=TRUE)
Quitting from lines 124-128 (chapter.Rnw) 
Error in parse(text = x, srcfile = src) : <text>:3:1: unexpected input
2: .chapter <- 7
3: \
Was it helpful?

Solution

Thou have forgotten about a call to the cat function:

cat("\\setcounter{chapter}{", .chapter-1, "}", sep="")
cat("\\setcounter{page}{", .pages[.chapter]-1, "}", sep="")

You may call these in a loop, together with cat("\\include{", filename[.chapter], "}", sep=""). This is how I typeset my R book (each chapter was compiled manually, and then the whole manuscript was generated via aggregation of the resulting .tex files).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top