Hello learnr2
A guided tour of learnr2 features
What is this?
learnr2 lets you write interactive R tutorials that run entirely in the student’s web browser using Quarto and WebR.
This tutorial is itself a learnr2 tutorial. Read it, edit the cells, and run them to see each feature work. Use Chrome or Edge for the best experience. Other browsers may not support voice recordings, which is a question type which learnr2 provides.
1. Runnable code cells
Every code cell is a live editor. Press Run Code (or Ctrl/Cmd + Enter) to execute it. Edit the code and run it again — it is yours to experiment with.
In the .qmd file, that cell is a {webr} chunk:
```{webr}
x <- c(4, 8, 15, 16, 23, 42)
mean(x)
```Throughout this tour, the source of each cell is shown beside it like this, because the page itself shows you only the result. A cell’s options go on #| lines at its top, which the page never displays. (Every chunk in a real tutorial also carries a #| label: line; check_tutorial() insists on it. The examples here leave it out.)
Output works the same as in R, including plots:
2. Non-editable cells
Sometimes you want to show code that runs but not allow students to edit it. Use the edit: false option when creating the code cell:
```{webr}
#| edit: false
sample(1:100, 5)
```3. Exercises
An exercise is a code cell the student is expected to complete. Mark a cell with the exercise option and give it a name. The cell starts empty (or with a leading comment, as below) and the student then edits it, and can run the code.
```{webr}
#| exercise: ex_sum
#| persist: true
# Compute the sum of the integers from 1 to 100.
```The persist: true option saves the student’s edits in the browser’s localStorage, keyed to this page and exercise. Refresh the page after editing the cell above — your changes are still there. But to see the output again, you must click Run Code again.
Hints
Add a .hint block naming the exercise. Students can reveal it when stuck. On the page it becomes the Show Hint button in the toolbar of the exercise cell above; in the .qmd it is a fenced div:
::: { .hint exercise="ex_sum" }
The `sum()` function adds numbers, and `1:100` is the sequence 1, 2, ..., 100.
:::The sum() function adds numbers, and 1:100 is the sequence 1, 2, …, 100.
Solutions
A .solution block reveals a model answer, behind a Show Solution button in that same toolbar (it appears once the hint has been shown):
::: { .solution exercise="ex_sum" }
```r
sum(1:100)
```
:::sum(1:100)4. Setup cells
Exercises often need objects to exist before the student starts. A cell marked setup: true for a given exercise runs invisibly beforehand. Here a setup cell pre-creates a vector the next exercise uses. You see only the exercise cell on the page; in the .qmd there are two:
```{webr}
#| setup: true
#| exercise: ex_mean
scores <- c(72, 88, 91, 64, 100)
```
```{webr}
#| exercise: ex_mean
#| persist: true
# `scores` already exists. Compute its mean.
```mean(scores)5. Automatic grading
learnr2 reuses ‘quarto-live’’s grading, which is powered by the gradethis package. Add a check cell for an exercise; it runs when the student presses Submit and compares their work against the solution.
A graded exercise needs its solution as a solution: true code cell (not the .solution fenced div used in section 3) — only the cell form emits the machine-readable copy of the code that gradethis::grade_this_code() compares against. The cell still renders a Show Solution button for the student, exactly like the div does. Three cells in the .qmd make the one graded exercise below: the exercise, its solution, and its check. Only the first is visible as a cell; the second is the Show Solution button and the third is the Submit button’s grader.
```{webr}
#| exercise: ex_grade
#| persist: true
# Multiply 6 by 7.
```
```{webr}
#| exercise: ex_grade
#| solution: true
6 * 7
```
```{webr}
#| exercise: ex_grade
#| check: true
gradethis::grade_this_code()
```6 * 7
6 * 7Try submitting a wrong answer (e.g. 6 + 7), then the right one, to see the feedback change.
6. Quiz questions
Not every check needs to run code. learnr2::question() adds a learnr-style quiz question. Questions render wherever the R code below is evaluated (a normal {r} chunk, since this runs once while you author the tutorial, not each time a student loads the page).
Single choice, with a nudge to try again:
learnr2::question(
"Which function computes the arithmetic mean in base R?",
learnr2::answer("mean()", correct = TRUE),
learnr2::answer("average()"),
learnr2::answer("avg()"),
allow_retry = TRUE
)Multiple choice is inferred automatically from how many answers are marked correct:
learnr2::question(
"Which of these are valid ways to create a vector in R?",
learnr2::answer("c(1, 2, 3)", correct = TRUE),
learnr2::answer("1:3", correct = TRUE),
learnr2::answer("vector(1, 2, 3)"),
random_answer_order = TRUE
)Free-text questions compare the student’s typed answer against one or more acceptable responses:
learnr2::question(
"What R package powers grading for learnr2 exercises?",
learnr2::answer("gradethis", correct = TRUE),
type = "text",
allow_retry = TRUE
)Some free-response questions have a definite right answer that’s too long or variable in phrasing to grade with an exact match. type = "reflection" handles that case: it shows the student a model answer after they submit their own response, without grading it — and locks their response so it can’t be changed afterward:
learnr2::question(
"Explain why the code cells on this page don't need a running R server.",
learnr2::answer(
"They execute in the student's own browser via WebR (R compiled to
WebAssembly), not on a remote server --- so the tutorial keeps working
even after wherever it was originally hosted goes offline.",
correct = TRUE
),
type = "reflection"
)type = "reflection_editable" works the same way, except that a submitted response can be reopened. Submit locks it behind an “Edit Answer” button, and Edit reopens it, with the button back to Submit and a note that the change isn’t saved until then. Reserve it for answers with nothing to copy: the minutes question at the end of a tutorial (see section 10), and a question whose answer is a URL of the student’s own, such as their repository’s address, since a mistyped URL is the commonest reason a student has to resubmit:
learnr2::question(
"Explain the difference between `type = \"text\"` and `type =
\"reflection\"`.",
learnr2::answer(
"`\"text\"` grades an exact match against one or more accepted answers;
`\"reflection\"` never grades anything, it just shows a model answer for
comparison.",
correct = TRUE
),
type = "reflection_editable"
)Often the prompt reads better as ordinary text on the page, especially when it runs to several sentences of instructions. Write it there and pass show_text = FALSE, so the question box shows only the answer field. text is still required: it is saved with the answer, read to screen-reader users, and used to name the question if the student tries to download without answering it. The tutorials in vscode.tutorials and misc.tutorials do this for every question:
Open a terminal and run date. Paste the command and its output below.
learnr2::question(
"Run `date` in a terminal and paste the command and its output.",
type = "reflection",
show_text = FALSE
)Submitted answers are saved automatically (again via localStorage, keyed by page URL and question) and restored on the student’s next visit. The default key is the question’s {r} chunk label, so rewording a question is safe — but renaming its chunk resets that question’s saved answers. Pass id = "some-stable-slug" to question() to pin the key regardless of the chunk label.
Group related questions with learnr2::quiz():
learnr2::quiz(
caption = "Quick check",
learnr2::question(
"2 + 2 equals?",
learnr2::answer("4", correct = TRUE),
learnr2::answer("22")
),
learnr2::question(
"Is R free and open source?",
learnr2::answer("Yes", correct = TRUE),
learnr2::answer("No")
)
)7. Copy/paste an image
For exercises where the student’s work is a plot or other image, add allow_image = TRUE to a "reflection"/"reflection_editable" question and let them paste a screenshot from their clipboard as their response — there is no file-upload button, just press Ctrl+V (or Cmd+V) with the response box focused (or click the box below it and paste there instead). Once an image is pasted it is the whole answer: the text box disappears and nothing typed is saved alongside it. “Remove image” brings the text box back.
Try it: edit the exercise below (or leave it as-is), run it, then take a screenshot of the plot it produces — e.g. Cmd+Shift+4 on a Mac, Win+Shift+S on Windows, or your Chromebook’s screenshot tool (Ctrl + Show windows) — and paste it into the question underneath.
learnr2::question(
"Paste a screenshot of the plot you made in the exercise above.",
learnr2::answer(
"A scatterplot of `wt` vs. `mpg`, colored steel blue.",
correct = TRUE
),
type = "reflection",
allow_image = TRUE
)A submitted screenshot can be replaced. A "reflection" question locks for good once submitted, but a screenshot question keeps an Edit Answer button: it reopens only the image box, the question counts as unsubmitted until a new image is submitted, and the Continue button below waits accordingly. Without it, a student who pasted the wrong screenshot had to Start Over the whole tutorial. Try it on the question above.
When a typed answer would prove nothing — “paste a screenshot of your GitHub dashboard” — make the question screenshot-only with allow_text = FALSE. No text box is shown, and Submit is refused until an image is pasted:
learnr2::question(
"Paste a screenshot of this page's table of contents.",
type = "reflection",
allow_image = TRUE,
allow_text = FALSE
)Whatever format your platform’s clipboard actually holds — it varies, so a screenshot isn’t guaranteed to be a PNG — allow_image accepts it: PNG, JPEG, GIF, WebP, or BMP. Before saving, it scales the image to at most 1600 pixels wide and stores it as a compact WebP (JPEG in Safari), so a page of screenshots doesn’t fill the browser’s storage. If a save ever fails, the page shows a warning and the answer stays unsubmitted (see the question() help page for the details).
8. Record your voice
For a question whose answer is best spoken — “explain, in a sentence or two, what this plot shows” — add allow_audio = TRUE to a "reflection" question. The student clicks Record, speaks, clicks Stop, listens back, and can record again before submitting. The recording is stored and downloaded exactly like a pasted screenshot: as a data URL inside the answers file, which extract_submission_media() turns back into a playable .webm file.
Use Chrome or Edge for voice questions. They are the browsers learnr2 is tested in; current Firefox and Safari record too, and the page checks before offering Record. If your tutorial has a voice question, tell students at the start to open it in Chrome or Edge. A student in a browser that cannot record sees a note in place of the Record button, and a notice at the top of the page before starting, and can carry their answers over to the right browser with Download Answers and Load Answers. The first Record shows the browser’s microphone prompt.
Try it:
learnr2::question(
"In a sentence or two, say what you have learned so far in this tutorial.",
type = "reflection",
allow_audio = TRUE,
allow_text = FALSE,
max_seconds = 60
)allow_text = FALSE makes it voice-only, as for screenshots. max_seconds caps the recording (two minutes by default, five at most) and the recorder stops by itself when it is reached. A submitted recording can be replaced through Edit Answer, like a screenshot. A recording costs about 3KB a second of the browser’s storage, so check_tutorial() warns when a tutorial’s voice questions add up to more than ten minutes.
9. Student info and submission
Two more pieces for wrapping a tutorial into something a student can turn in, no server required. In a real tutorial, student_info() normally goes at the very top and download_answers_button() at the very bottom; they’re shown together here just for the demo.
student_info() collects identifying information (name, email, an optional ID by default). It’s deliberately not a quiz question — there is nothing to grade and no model answer, just a plain form with its own Submit button. It also auto-saves as the student types, so nothing is lost even if they never click Submit:
learnr2::student_info()download_answers_button() gathers every question() and student_info() answer already saved on the page into one readable JSON file and downloads it — so a student can save their work and turn it in (attach to an email, upload to an LMS), all without a server to submit to. The file opens with what it is a submission for: the tutorial’s package and that package’s version, the tutorial’s name and title, and the learnr2 version, all filled in when the tutorial was rendered. The download also carries browser info, a per-device id, and a time field: the moment the student clicked “Download”, lightly obfuscated so the raw timestamp isn’t readable or hand-editable in the file. Recover it with learnr2::submission_time(path), and give the whole file back to learnr2::load_tutorial(path) to reopen the tutorial with every answer filled in, for a student who needs to fix one. The file ends with a fingerprint, a hash of its own contents that learnr2::check_submission(path) recomputes, so a name or an answer edited by hand in the file shows up, and with loadedFrom, which records the earlier file a resubmission was restored from. With no server involved nothing can prevent a determined student from editing their answers; these make the ordinary case visible:
learnr2::download_answers_button(filename_prefix = "hello-learnr2")10. Layout options
Nothing in this section is a widget. It describes the page-level choices an author has, all made in the YAML header or with one function call, and what each one does for the student.
Table of contents
Every tutorial scaffolded by create_tutorial() has toc: true in its YAML header, which gives the page Quarto’s table-of-contents sidebar: the list of sections on the right of this page. Set toc: false to drop it.
The sidebar is a map, not a shortcut. Sections reveal one at a time behind Continue buttons whether or not there is a TOC; the TOC adds a view of the whole tutorial’s shape and of how far the student has come. On a phone-width screen Quarto hides the sidebar on its own, so a toc: true tutorial behaves like a toc: false one there, with no author action.
Submitting before continuing
By default, the Continue button at the end of a section stays greyed out, with a note under it, until every question and student-info form above it has been submitted. A student can type anything, but must submit something before moving on, and a type = "reflection" question locks once submitted. Together those two rules let a tutorial show its own answer immediately after the student’s, which is what we always want, without inviting anyone to paste our answer back into their box: by the time they see ours, theirs is in and cannot be changed.
This tour is reference material, so it switches the gate off with the chunk below (shown here; hidden in a real tutorial with echo: false). That is why you have been able to click past every question on this page without answering it. Leave this chunk out of a tutorial of your own and the gate is on.
learnr2::tutorial_options(require_submission = FALSE)Skipping ahead
By default the TOC cannot be used to read ahead. Look at the sidebar now: the entries below this section are dimmed, a click on one does nothing, and each lights up only when its section is unlocked. A student can see what is coming and where they are, but cannot open the whole tutorial at once.
If you want students to roam freely — reference material, or a tour like this one — turn on skipping too, in that same tutorial_options() call:
learnr2::tutorial_options(allow_skip = TRUE, require_submission = FALSE)Then clicking any TOC entry unlocks every section up to that one and jumps there, like a classic learnr tutorial with allow_skip: yes. This page leaves skipping at its default so you can see the dimming in action. Without a TOC the setting has no effect, since there is nothing to click.
Pauses without a heading
Not every Continue stop needs a title. A line holding only ###, with nothing after it, is a pause: the content below it stays hidden until the student clicks a button that says just Continue, and no heading is shown. The tutorial.helpers house style puts two of these inside every exercise, one before the author’s own answer and one before the knowledge drop, so the student compares before they read on. Here is one now.
You just clicked through a pause. In the .qmd it is three hash marks on a line by themselves; in the sidebar it has no entry.
Language
Everything learnr2 writes on the page — Continue, Start Over, Submit Answer, the feedback, the notes and error messages, the default labels of student_info() — follows the document’s language, which is Quarto’s own lang: key in the YAML header. A tutorial with lang: fr gets a French table of contents from Quarto and French buttons from learnr2, with the Run Code, Show Hint and Show Solution buttons and the Exercise captions of the code cells relabelled too. The prose is the author’s, in whatever language they write it.
learnr2 ships English and French. A language it has no translation for falls back to English, and check_tutorial() warns about it. To reword single strings, pass language to tutorial_options():
learnr2::tutorial_options(language = list(continue = "Next"))The keys are those of system.file("extdata/quiz/lang/en.json", package = "learnr2"). Translations are welcome: see the “Language” section of the “Translating learnr Tutorials” vignette.
Start Over
Every answer, pasted image, and exercise edit on a page is saved in the student’s browser, so reloading never loses anything. The way to wipe it all is the Start Over button, which learnr2 adds to every tutorial automatically — nothing to write in the .qmd. It asks for confirmation, then clears this page’s saved state (but not the per-device id that download_answers_button() records) and reloads.
Where it appears follows the layout. With a visible sidebar it sits at the bottom of the table of contents, as it does on this page. Without one — toc: false, or a screen too narrow for the sidebar — it moves to the top of the tutorial, directly under the title, where it stays visible no matter how far the student has progressed. Either way the student always has exactly one.
Beside it sit two more. Download Answers downloads the same file as the button at the end of the tutorial, from wherever the student is, revealing nothing: a student who stops part-way can hand in what they did, and the file’s progress field says how far they got. Load Answers is the way back from a downloaded file. A student who downloaded their answers and has to change one (a mistyped URL, say) picks that file, or drops it anywhere on the page, and every answer in it is filled in as if just submitted, with the page open where they left off; locked questions stay locked, editable ones stay editable. The same thing from R is learnr2::load_tutorial(path), which also renders the tutorial first, so it suits a student working in a Codespace; the button needs no R at all, so it works on a published copy of the page.
11. Code, commands, and output
Tutorials constantly show text a student must type, and text they should expect to see back. The two need to look different from each other, and both need to look different from prose. This section shows the choices learnr2 makes and the options you have.
Something to type: name the language
Quarto boxes a fenced block, colours it, and gives it a copy button only when the block names its language:
ls -aThat is written as:
```bash
ls -a
```Use bash for the bash Terminal, r for the R Terminal, and yaml for a YAML header. Text to type that is in no language, such as a prompt for an AI or a commit message, takes default, which boxes it with a copy button and colours nothing. The copy button matters: a student who copies show_file("analysis.qmd", chunk = "Last") gets it right the first time.
Where to run it: add a label
Many instructions boil down to “run this in the bash Terminal, not the R one”. A label puts that on the block itself, in a bar above it:
bash Terminal
quarto render analysis.qmd```{.bash filename="bash Terminal"}
quarto render analysis.qmd
```Something to compare against: mark it as output
Expected output — a transcript of ls, or the answer shown after Continue — should not look like a command, or some students will type it. Mark it {.output} and it gets a lighter style, with a grey left edge and no copy button:
codespace-starter $ ls -a
. .. .devcontainer .git
```{.output}
codespace-starter $ ls -a
. .. .devcontainer .git
```Output that R itself prints gets the same style automatically, both from a {webr} cell (see section 1) and from an {r} chunk in the tutorial:
mean(c(4, 8, 15, 16, 23, 42))[1] 18
A block with no language
A bare ``` fence gets only a monospace font from Quarto, which on the page reads as oddly-typeset prose. learnr2 gives it the same grey box as a tagged block, so it still reads as code, but it gets no colours and no copy button:
ls -a
Tag it anyway. Tutorials translated from tutorial.helpers use bare fences for everything, commands and transcripts alike, which is why learnr2 boxes them by default.
Code inside a sentence
Single backticks, as in “run whoami”, give inline code a monospace font and a light tint. Use them for anything typed at the keyboard: commands, file names, function names such as mean(), and keys such as Ctrl + C.
Where to go next
- Use
learnr2::create_tutorial("my-tutorial", dir = ".")to scaffold your own. - Edit the
.qmd, then runlearnr2::check_tutorial()on its directory to catch the common authoring mistakes, andlearnr2::render_tutorials()(or plain Quarto) to build it. - Preview the result with
learnr2::run_tutorial(), which renders, serves and opens it in your browser.