Learnr exercise hints: How to show randomly generated values

I would like to be able to write exercise hints displaying randomly generated values. Here's a MWE:

---
title: "learnr"
output: learnr::tutorial
runtime: shiny_prerendered
---

```{r setup, include = FALSE}
library(learnr)
vals <- sample(1:10, 3)
```

## Edit hints of an exercise

**Question:** How can you compute the mean of the values `r paste0(vals, collapse=", ")` in R?

```{r ex1, exercise = TRUE}

```

```{r ex1-solution}
# Here, I would like to render the R code
mean( c(vals[1], vals[2], vals[3]) )
# where vals[i] are the values which appear in the question.
# I can't just type them in since they are randomly generated.
```

Press the Solution button to see the problem.

You can see how it looks below:

How can this be done?
Thank you in advance.

Unfortunately, using random values is difficult to do with learnr tutorials, for two reasons.

The first is that learnr tutorials involve two rendering stages and the global setup code is evaluated once in each stage, separately and at different times:

  1. The setup code is first evaluated during the pre-render step. The randomly generated values then appear in the static portion of the tutorial, e.g. 4, 2, 8 in the prompt above the exercise in the screenshot below.
  2. The setup code is then evaluated again to start up the Shiny app that runs the tutorial. If you evaluate vals in the interactive code box, you see that it now has a different value — 5, 3, 10 in the screenshot below.

The only way around this is to set a seed at the start of the setup chunk, but as you can imagine this would ultimately remove the dynamic aspect of randomly selecting values for use in questions.

The second reason this isn't possible is because the solution code is technically never evaluated unless it's used by grading code (such as with gradethis). So the solution code is presented as-is when used as a hint.

1 Like

Hi grrrck,

Thanks a lot for the feedback.
Ok, then I will have to work my way around this limitation.

Many thanks,
bruce

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.