An R script for calculating the reading time of an R Markdown file

Because life is short.

Reading time: 2 minute(s) @ 200 WPM.

To see how we just did that, read on.

Because psychological research tells us that including estimated reading times can increase reader engagement with digital content, I decided to include reading times for my riveting posts.

So I wrote a simple R script. Here it is, as an R code chunk:

```{r echo=FALSE}
bytes <- file.size("Your_File_Name.Rmd")
words <- bytes/10
minutes <- words/200
```

The script is very simple, such that even I could program it. We first get the number of bytes in the R Markdown file specified in the argument to the file.size() function. A byte is basically equivalent to a single character, and because a typical text word is 10 bytes, we divide bytes by 10 to get the approximate number of words in the document. And because more research suggests that the average adult human can read 200-250 words in one minute, we divide the number of words by 200 to get a conservative estimate of the number of minutes it would take an average person to read the number of words in the document. This only takes into account reading the text. Time involved in studying figures, following hyperlinks, rumination, and so forth are ignored in this simple computation. So the estimated reading time is most likely a minimum reading time. But at least it gives you a ballpark estimate of how long it might take to read the document.

The code chunk must be inserted into each R Markdown file for which you want to compute reading time (the script will only work for R Markdown documents). You also have to insert the file name of the R Markdown document that contains the script as an argument to the file.size() function, which is part of the Base R distribution.

Then, in the text of your document, reference the minutes variable like this, using inline R code inside of a pair of backticks:

Reading time: `r round(minutes)` minute(s) @ 200 WPM.

This will result, for the text of this post, in:

Reading time: 2 minute(s) @ 200 WPM.

Note that the inline code uses the R round() function to round the number of reading minutes to the nearest integer (using the default value of 0 decimal places).

For all of this to work, the script has to be placed in the R Markdown file before the point at which you reference the minutes variable, or else the inline code won’t know about the minutes variable.

 Share!

 
comments powered by Disqus