## 14.3 Exercises

Exercises are interactive R code chunks that allow readers to directly execute R code and see its results. We have shown a simple exercise in Figure 14.2.

Exercises can include hints or solutions as well as custom checking code to provide feedback on user answers.

### 14.3.1 Solutions

To create a solution to an exercise in a code chunk with the chunk label foo, you add a new code chunk with the chunk label foo-solution, e.g.,

{r filter, exercise=TRUE}
# Change the filter to select February rather than January
nycflights <- filter(nycflights, month == 1)


{r filter-solution}
nycflights <- filter(nycflights, month == 2)


When a solution code chunk is provided, there will be a Solution button on the exercise (see Figure 14.3). Users can click this button to see the solution.

### 14.3.2 Hints

Sometimes you may not want to give the solutions directly to students, but provide hints instead to guide them. Hints can be either Markdown-based text content or code snippets.

To create a hint based on custom Markdown content, add a <div> tag with an id attribute that marks it as hint for your exercise (e.g., filter-hint). For example:

{r filter, exercise=TRUE}
# filter the flights table to include only United and
# American flights
flights


<div id="filter-hint">
**Hint:** You may want to use the dplyr filter function.
</div>

The content within the <div> will be displayed underneath the R code editor for the exercise whenever the user presses the Hint button.

If your Pandoc version is higher than 2.0 (check rmarkdown::pandoc_version()), you can also use the alternative syntax to write the <div>:

:::{#filter-hint}
**Hint:** You may want to use the dplyr filter function.
:::

To create a hint with a code snippet, you add a new code chunk with the label suffix -hint, e.g.,

{r filter, exercise=TRUE}
# filter the flights table to include only United and
# American flights
flights


{r filter-hint}
filter(flights, ...)


You can also provide a sequence of hints that reveal progressively more of the solution as desired by the user. To do this, create a sequence of indexed hint chunks (e.g., -hint-1, -hint-2, -hint-3, etc.) for your exercise chunk. For example:

{r filter, exercise=TRUE}
# filter the flights table to include only United and
# American flights
flights


{r filter-hint-1}
filter(flights, ...)


{r filter-hint-2}
filter(flights, UniqueCarrier == "AA")


{r filter-hint-3}
filter(flights, UniqueCarrier == "AA" | UniqueCarrier == "UA")