1

Using R exams, I am developing a pdf exam with several questions (hence several Rmd files) but the questions are connected and would use a dataset created in the first question file. Questions would not be amenable to a cloze format.

Is there a way to write the exercises so that the second exercise can access the data generated by the first exercise ?

djourd1
  • 459
  • 4
  • 14

3 Answers3

1

Is it an option to save the data you need to disk in one Rmd file

```{r, echo=FALSE}
saveRDS(df, "my_stored_data.rds")
```

and then load it in the other one

```{r, echo=FALSE}
readRDS(df, "my_stored_data.rds")
```
Georgery
  • 7,643
  • 1
  • 19
  • 52
1

Another option could be to knit the Rmd files from an R script and then knit them from this R script. If you do that, the Rmd files use the environment of the R script (!) instead of creating their own. Hence you can use the same objects (and therefore of course let one Rmd script store the data, while the other uses it as input.

In this thread: Create sections through a loop with knitr there is a post from me about doing this. It's basically this:

The first Rmd file:

---
title: "Script 1"
output: html_document
---

```{r setup, include=FALSE}
a_data_frame_created_in_script_1 <- mtcars
```

saved as rmd_test.Rmd

The second one:

---
title: "Script 1"
output: html_document
---

```{r setup}
a_data_frame_created_in_script_1
```

saved as rmd_test_2.Rmd.

And then you have an R-script that does this:

rmarkdown::render("rmd_test.Rmd", output_file = "rmd_test.html")
rmarkdown::render("rmd_test_2.Rmd", output_file = "rmd_test_2.html")
Georgery
  • 7,643
  • 1
  • 19
  • 52
  • Thanks for this additional tip. Would suspect this adds another layer of complexity in the writing of the exercises though. – djourd1 Jun 30 '20 at 11:46
  • Edited the answer. Of course, I don't know your exercises, but I have the feeling, that this actually an elegant solution. – Georgery Jun 30 '20 at 11:53
1

The easiest solution is to use a shared environment across the different exercises, in the simplest case the .GlobalEnv. Then you can simply do

exams2pdf(c("ex1.Rmd", "ex2.Rmd"), envir = .GlobalEnv)

and then both exercises will create their variables in the global environment and can re-use existing variables from there. Instead of the .GlobalEnv you can also create myenv <- new.env() and use envir = myenv.

For Rnw (as opposed to Rmd) exercises, it is not necessary to set this option because Sweave() Rnw exercises are always processed in the current environment anyway.

Note that these approaches only work for those exams2xyz() interfaces, where the n-th random draw from each exercise can be assured to end up together in the n-the exam. This is the case for PDF output but not for many of the learning management system outputs (Moodle, Canvas, etc.). See: Sharing a random CSV data set across exercises with exams2moodle()

Achim Zeileis
  • 15,710
  • 1
  • 39
  • 49