tl/dr: Use reticulate to pass variables between R and python.
Chained setup chunks
Before rstudio/learnr#390, the most complicated arrangement an exercise could have is "setup R chunk > exercise setup setupA R chunk > exercise ex1 R chunk (with user's code)".
Ex:
```{r setup, include = FALSE}
library(learnr)
d <- 3
```
```{r setupA}
a <- 5
```
```{r myexercise, exercise=TRUE, exercise.setup = "setupA"}
x <- a + d + 1
x # 9
```
After rstudio/learnr#390, exercise.setup can be recursively followed and each Rmd chunk will be used. In addition, exercise.setup and exercise chunks can use other languages that are supported by Rmd / knitr. Ex: python, MySQL, and bash.
To expand on the prior example, you are now allowed more than one exercise.setup chunk. When submitting an ex1 user exercise, these chunks will be run: setup R chunk > exercise setup setupA R chunk > exercise setup setupB R chunk, exercise ex1 R chunk (with user's code)
(Modified from rstudio/learnr@5a061d03 setup-chunks.Rmd)
```{r setup, include = FALSE}
library(learnr)
d <- 3
```
```{r setupA}
a <- 5
```
```{r setupB, exercise.setup = "setupA"}
b <- a + d
```
```{r ex1, exercise=TRUE, exercise.setup = "setupB"}
x <- b + 1
x # 9
```
Mixing python and R in {learnr} exercises
@vnijs You are correct in that the python and R sessions will behave as different processes with no automatic communication.
To get around this issue, authors should use reticulate as it handles creating a bridge from R to python and python to R just by calling library(reticulate) in a setup chunk.
Full document example:
---
title: "Chained setup chunks"
output: learnr::tutorial
runtime: shiny_prerendered
---
```{r setup, include = FALSE}
library(learnr)
library(reticulate)
```
```{r even_more_setup}
d <- 3
```
# learnr + reticulate demo
<!-- Create Python variable `a` which reads `d` from R: -->
```{python setupA, exercise.setup = "even_more_setup"}
a = r.d + 2 # 5
```
<!-- Read `a` from Python, and create `b`: -->
```{r setupB, exercise.setup = "setupA"}
b <- py$a + d # 8
```
R exercise that uses `b` (via R and python setup chunks):
```{r ex1, exercise = TRUE, exercise.setup = "setupB"}
b + 1 # 9
```
Python exercise using `b` (via R and python setup chunks):
```{python ex2, exercise = TRUE, exercise.setup = "setupB"}
r.b + 1 # 9
```
(small disclosure, found + fixed setup chunk engine bug in rstudio/learnr#440 when making this demo)