Selectively hide text with JavaScript in RMarkdown

I guess this is one of those where I kind of did know it was possible, really. If I’d thought it through. But I’ve always not been sure how easy it would be and I’ve been in too much of a rush.

So I’m trying to move my organisation onto HTML instead of Word. HTML is easier to output and parse, and it’s interactive with a bit of JavaScript. I used the DT package in R to put some tables into an RMarkdown document and of course that’s very nice because they’re pageable, orderable, and searchable out of the box.

But there’s often a lot of text that I’m not sure everyone will be interested in. We collect a lot of comments and some people want every single one. Some people just want the tables. So it would be nice to be able to selectively show and hide the text in each section.

And I did know this, really. But RMarkdown documents accept pure HTML. And pure JavaScript. So it’s embarrassingly easy. Ridiculously easy. Here’s one. I half stole it from

title: "JavaScript test"
author: "Chris Beeley"
date: "11 May 2018"
output: html_document

function myFunction() {
    var x = document.getElementById("myDIV");
    if ( === "none") { = "block";
    } else { = "none";

<button onclick="myFunction()">Show/ hide</button>

<div id="myDIV">

Some comments here.

There are lots so it's nice.

To be able to hide them.


That’s it. Boom. Done. If you’re not all doing that by the middle of next week then you need to be asking yourselves why.

Recoding to NA with dplyr

Just very quickly again, still horribly busy, but this has been annoying me for ages and I finally figured it out. When you’re using recode from dplyr, you can’t recode to NA if you’re recoding to other things that aren’t NA, because it complains that the types aren’t compatible. So don’t do this:

  mutate(Relationship = recode(Relationship, "Co-Habiting" = "Co", 
    "Divorced" = "Di", "Married" = "Ma", "Civil partnership" = "CI"
    "Single" = "Si", "Widowed" = "Wi", "Separated" = "Se", 
    "Prefer not to say" = NA))

Use na_if() instead:

  mutate(Relationship = recode(Relationship, "Co-Habiting" = "Co", 
    "Divorced" = "Di", "Married" = "Ma", "Single" = "Si", 
    "Widowed" = "Wi", "Separated" = "Se", "Civil partnership" = "CI")) %>%
  mutate(Relationship = na_if(Relationship, "Prefer not to say", NA))

Checking memory usage in R

Wow, I cannot believe I didn’t blog this. I just tried to find it on my own blog and I must have forgotten. Anyway, it’s an answer I gave on Stack Overflow a little while ago, to do with measuring how much memory your R objects are using.



## 88 B

## 832 B

## 6.74 kB

This is from Hadley Wickham’s advanced R.