Learnr exercise hints: How to show randomly generated values

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