Generate HTML reports from R scripts

Published: Thu 01 September 2016

Tags: R Python

Several tools exist to automatically produce well-formatted reports from R code, such as knitr and Sweave. Those tools don't actually process raw R scripts, but requires specific file formats enabling literate programming such as R Markdown or LaTeX.

Those formats enable precise control of the desired output, but the R code in them is embedded into special blocks and cannot be run directly by R. I do like the idea of generating automatic reports with knitr or Sweave, but I would like it even better if I could keep a simple functional R script with only "rich" comments!

pyR2html is a light wrapper around knitr I wrote to convert a pure R script into an HTML report. It is possible to use very simple comment formats to specify headers and text. Its functionality is much simpler than knitr, but I am happy that it enables me to keep clean, readable R scripts and to generate HTML report to share with my collaborators in one go!

If you feel interested, have a look at the GitHub page for instructions about installation and use!

1 A minimal example

Here is a simple example of an R script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
### * This is my top header

# Let's start with some regular text, and then perform a computation of the
# highest interest:
x = rnorm(10)
## y is x + some noise
y = x + rnorm(10)

### * This is another top header

### ** This is a second level header

# In this section we will do a plot of our data:
plot(x, y, xlab = "My X values", ylab = "Some Y values")

### *** Third level

s = sample(c("Lorem", "Ipsum"), 10, replace = T)
s

### *** Third level again

# Don't forget the session info for reproducible code!
sessionInfo()

### ** Another one on second level

# Note that you have access to a table of content of the left side of the page.

# Maybe another plot?
plot(x, sin(x) + y)

Convert a script myScript.R to HTML format with:

1
pyR2html myScript.R

You can see the HTML output here!

2 To go further…

2.1 For Emacs users

You might have noticed that the structure of the header is determined by:

1
2
3
4
5
### * My header of level 1
...
### ** My header of level 2
### *** Level 3
...

The number of stars determines the depth of the header. You can use it conveniently in the Emacs text editor to fold code using orgstruct. You can add the following line to your .emacs:

1
2
3
4
5
(add-hook 'ess-mode-hook
	  '(lambda ()
	     (orgstruct-mode)
	     (setq outline-regexp "[ ]*### ")
	     (setq orgstruct-heading-prefix-regexp "[ ]*### ")))

Now you can use TAB and SHIFT+TAB when the cursor is on one of the headers to cycle through the different visibility levels.

2.2 CSS style

The default style of the HTML page might not suit your taste. If you don't appreciate its artistic qualities, you can of course customize the CSS code which is incorporated in the HTML file :)