Hidden Solutions


The R for Reproducible Scientific Analysis pages at software carpentry have a really nice interface for hiding and showing solutions to exercises. I’ve created my own lightweight solution that you can use in any html file, including those made by RMarkdown (e.g., R notebooks).


Graph the relationship between speed and distance for the cars dataset.

You can put some text inside the solution, as well as code cunks.

ggplot(cars, aes(speed, dist)) +
  geom_point(color = "purple") +
  geom_smooth(method = "lm", color = "purple")
## `geom_smooth()` using formula 'y ~ x'

Setting this up requires a few lines at the beginning and end of each file, plus surrounding your solutions with a line of html.

Put this at the beginning of your file

  /* styles for hidden solutions */
  .solution {
    height: 2em;
    overflow-y: hidden;
    padding: 0.5em;
  .solution.open { 
    height: auto; 
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
  .solution button {
    height: 1.5em;
    margin-bottom: 0.5em;
  .solution pre.sourceCode {
    border-color: green;

If you’re using RMarkdown Websites, you can just put these lines of css into an external stylesheet linked in your _site.yml file (e.g., rguppies.css).

Put this at the end of your file

  window.onload = function(){
    var buttons = document.getElementsByTagName("button");
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].onclick = function() {
        var cl = this.parentElement.classList;
        if (cl.contains('open')) {
        } else {

If you’re using RMarkdown Websites, you can just put this script into an external footer or script file linked in your _site.yml file (e.g., rguppies.js).

Surround your hidden solutions like this

<div class="solution"><button>Solution</button>

PUT YOUR SOLUTION HERE (including r chunks)


You can change the text on the button to something else (e.g., <button>View the Answer</button>).

Let me know if you have any suggestions or find this useful.

Lisa DeBruine
Lisa DeBruine
Professor of Psychology

Lisa DeBruine is a professor of psychology at the University of Glasgow. Her substantive research is on the social perception of faces and kinship. Her meta-science interests include team science (especially the Psychological Science Accelerator), open documentation, data simulation, web-based tools for data collection and stimulus generation, and teaching computational reproducibility.