knitr Rnw file have optional output in child

61 views Asked by At

I use Rnw files to create exams for my students, I put separate quiz into child Rnw file and include them in the main Rnw in the way

<<child="xx.Rnw">>@

The xx.Rnw contains the problem statement and also the answer. I want to have two versions of the exam, one without the answer and one with the answer. Which means I need something that could conditionally generate two types of pdf.

The answer part is a mixer of <<>>@ code and latex. Anyone has a good idea how to do this in an agile way? Thanks!

1

There are 1 answers

0
Prevost On

For each problem statement you could create 2 child rnw chunks. The first chunk calls the rnw without the answers and the second chunk calls the rnw with the answer. At the beginning of the rnw document, create 2 variables called hide_answer and show_answer and set the eval chunk option of the child rnw chunks that omit the answer to hide_answer and set the eval chunk option of the child rnw chunks that show the answer to show_answer.

Then all you have to do is set the variables to TRUE or FALSE to generate the desired PDF.

<<r_load>>=
hide_answer = TRUE
if (hide_answer == TRUE) {
  show_answer = FALSE
} else {
  show_answer = TRUE
}
@

\documentclass{article}

\begin{document}

<<child_hide_answer, child=problem1_no_answer.rnw, eval=hide_answer>>=
@

<<child_shower_answer, child=problem1_with_answer.rnw, eval=show_answer>>=
@

\end{document}