# R-devel in parallel to regular R installation

Unfortunately, you need both: R-devel (development version of R) if you want to submit your packages to CRAN, and regular R for your research (you don’t want the unstable release for that).

Fortunately, installing R-devel in parallel is less trouble than one might think.

Say, we want to install R-devel into a directory called ~/R-devel/, and we will download the sources to ~/src/. We will first set up two environment variables to hold these two directories:

export RSOURCES=~/src
export RDEVEL=~/R-devel


Then we get the sources with SVN:

mkdir -p $RSOURCES cd$RSOURCES
svn co https://svn.r-project.org/R/trunk R-devel
R-devel/tools/rsync-recommended


Then, we compile R-devel:

mkdir -p $RDEVEL cd$RDEVEL
$RSOURCES/R-devel/configure && make -j  That's it. Now we just need to set up a script to launch the development version of R: #!/bin/bash export PATH="$RDEVEL/bin/:\$PATH" export R_LIBS=$RDEVEL/library
R "$@"  You need to save the script in an executable file somewhere in your $PATH, e.g. ~/bin might be a good idea.

Here are commands that make this script automatically in ~/bin/Rdev:

cat <<EOF>~/bin/Rdev;
#!/bin/bash

export R_LIBS=$RDEVEL/library export PATH="$RDEVEL/bin/:\$PATH" R "\$@"
EOF
chmod a+x ~/bin/Rdev


One last thing remaining is to populate the library with packages necessary for the R-devel to run and check the packages, in my case c("knitr", "devtools", "ellipse", "Rcpp", "extrafont", "RColorBrewer", "beeswarm", "testthat", "XML", "rmarkdown" ) and others (I keep expanding this list while checking my packages). Also, bioconductor packages limma and org.Hs.eg.db, which I need for a package which I build.

Now I can check my packages with Rdev CMD build xyz / Rdev CMD check xyz_xyz.tar.gz

# Presentations in (R)markdown

There are many ways to turn a markdown or Rmarkdown document into a presentation. Way too many, and none of them is perfect. I made my first presentation with knitr / Rmarkdown for the tmod package.

After trying various options in knitr, I decided on an approach in which the Rmarkdown document is oblivious of the presentation system and the job of turning it into a presentation is taken up by pandoc. There were several bumps and problems, and I will give now a step – by – step guide.

# 1. Input file

Let’s start with an example Rmd. In the following, I assume it has been saved under “test.Rmd”.

---
title: "Example presentation"
author: January Weiner
date: "r Sys.Date()"
---

# First part
## Slide 1
Code:

{r plot1}
plot(1:10, 1:10)


## Slide 2
Some maths: $sum_{i=1}^{N}$

# Second part
## Slide 3
... contents ...


# 2. From Rmarkdown to markdown

I use knitr only to create a markdown file.

Rscript -e 'knitr::knit("test.Rmd")'


This produces the file test.md. With that, knitr’s job is finished, we will not need it anymore.

I decided for reveal.js. It was easy to work with and adapt to my needs, it had elegant default themes, it has a low footprint and shortcuts. And it has the “2D” layout, meaning that sections (level one headers) are arranged horizontally, while slides within one section are arranged vertically. Pressing “Esc” in a presentation shows the slide overview:

Anyway, download reveal.js and unpack it in the same directory as test.md.

# Making the presentation

Use pandoc to create the reveal.js presentation. Note that this is not the final command line; in the following points I will discuss the problems which will influence the final version.

pandoc -s -S -t revealjs --mathjax -o test.html test.md


# 4. MathJax

On slide 2, we have a bit of maths. The maths is written in a LaTeX-like notation, and there are many ways to turn it into an elegant mathematical equation on the final presentation. I have tried many options with pandoc, and found that only MathJax works properly and without a major hassle. This is why on the previous command line I used the option --mathjax.

However, if you run the above command line, you will notice that on “Slide 2″, the maths doesn’t work, despite using the ‘–mathjax’ option. It would work, though, if we put the file on a server. The reason is that pandoc puts the URL to MathJax in the form ‘src=”//cdn.mathjax…”‘. This assumes the context of how we opened the file. If we opened it from a server, using http or https, this would have worked. If we open it directly in a browser, it uses “file://cdn.mathjax…” which is obviously not on our file system. We have two options.

## 4.1 External MathJax

Use the command line

pandoc -s -S -t revealjs --mathjax="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" -o test.html test.md


This works unless we have no Internet access, for example because we show our presentation in another institute, where our laptop cannot connect to the Internet, because then we are screwed.

## 4.2 Local MathJax

wget https://github.com/mathjax/MathJax/archive/v2.5-latest.zip
unzip v2.5-latest.zip
mv MathJax-2.5-latest/ MathJax


and specify the local installation with the following command line:

pandoc -s -S -t revealjs --mathjax="MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML" -o test.html test.md


This works, but our presentation has suddenly over 170 megabytes. Which sucks.

# 5. 2D layout and section headers

I mentioned previously that reveal.js allows a neat 2D layout, in which slides from one section are arranged vertically, and sections are put next to each other. However, sections with only a title and no contents might be a bit boring, so let us modify the .md file changing the second section as follows:

# Second part

This is the second part, even more interesting.

## Slide 3
... contents ...


You run pandoc again, and…

Huh, where is the 2D layout gone? Why are all slides next to each other? Why are all slides from one section all on one single slide?

Pandoc automatically guesses which level header denotes boundaries between slides. It defines “slide level” as “the highest level followed immediately by non-header contents”. After our modification, the top level header (starting with a single #) became the level at which slides are separated. OK, so maybe we try specifying the slide level manually?

pandoc -s -S -t revealjs --mathjax="MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML" -o test.html test.md


OK, this works, but… the contents under the first level header (“This is the second part…”) is gone! This is because “Headers above the slide level in the hierarchy create “title slides,” which just contain the section title and help to break the slide show into sections.”

Turns out that there is no way we can have both: 2D with slides divided neatly into sections, and section slides which contain more than just a title. Not if we use pandoc, that is.

# 6. Modifying the layout

## 6.1 reveal.js theme

This is the easiest part: pick one of the existing reveal.js themes (I omit the mathjax command line for simplicity sake, do remember to put it back in):

pandoc -s -S -t revealjs -o test.html test.md -V theme=blood


Note that the themes listed on the reveal.js website start with a capital letter, but you must specify a lowercase letter in the above command line.

## 6.2 Fine tuning the theme

I did not like the sans-serif, capitalized and decorated fonts of the blood theme (shadows on titles, I beg you). Ugly. However, if you know a little CSS (and you’d better learn it!), you can easily adapt it to your needs.

Look up the file reveal.js/css/theme/blood.css for hints and create your own CSS file (let us call it test.css) in the same directory as test.md. In the file below, I reset all the ugly decorations and set two fonts for headers and body, respectively: Garamond for headers, and Quattrocento Sans for body, using the google fonts service:

@import url('http://fonts.googleapis.com/css?family=EB+Garamond');

.reveal {
font-size: 32px;
font-family: 'Quattrocento Sans', 'sans-serif'; }

.reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6 {
font-family: 'EB Garamond', 'serif';
font-weight:normal;
text-transform: none;

.reveal h1 { font-size: 2em; }
.reveal h2 { font-size: 1.7em; }
.reveal h3 { font-size: 1.4em; }
.reveal h4 { font-size: 1em; }


Also, as you might notice, I prefer smaller fonts here. We integrate our test.css file with the following option

pandoc -s -S -t revealjs -o test.html test.md -V theme=blood --css test.css


You can add a logo (or whatever other background for your slides) by modifying the CSS file test.css. If logo.png is the name of your logo, adding this to your CSS will put it on all your slides in the top left corner:

body {
background-image: url(logo.png);
background-repeat: no-repeat;
background-position:20px 20px;
}


## 6.4 Better syntax highliting

Pandoc’s syntax highlighting doesn’t look good on a dark background. You can add the following to the “test.css” file to reproduce the Solarized theme.

.reveal pre code { color: #839496;
background-color: #2B2B2B; } /* use #FDF6E3 for light background */

.sourceCode .kw { color: #268BD2; }
.sourceCode .dt { color: #268BD2; }
.sourceCode .dv, .sourceCode .bn, .sourceCode .fl { color: #D33682; }
.sourceCode .ch { color: #DC322F; }
.sourceCode .st { color: #2AA198; }
.sourceCode .co { color: #93A1A1; }
.sourceCode .ot { color: #A57800; }
.sourceCode .al { color: #CB4B16; font-weight: bold; }
.sourceCode .fu { color: #268BD2; }
.sourceCode .re { }
.sourceCode .er { color: #D30102; font-weight: bold; }
}

# 7. Creating a PDF of your presentation

Of course you need a PDF for printing and as a backup.

There are two ways for producing PDF from reveal.js. Each one is imperfect.

## 7.1 Creating PDF using pandoc

Since the test.md file is a generic markup, we can turn it into a simple PDF

bash
pandoc -s -S -o test.pdf test.md


Or even beamer presentation:

pandoc -s -S -t beamer -o test.pdf test.md


Unfortunately, this is not so nice as our presentation, and completely ignores whatever we have put in the CSS.

## 7.2 Using the reveal.js printing facility and Google Chrome

The second way is interactive only (you cannot create the PDF with a command line). Open the file in google chrome and add ?print-pdf to the file URL, such that the end of the URL reads test.html?print-pdf.

The output looks garbled: the slides overlap. Don’t worry, it’s OK. Open the print dialog (press Ctrl-P), and you will see that now the output is correct. You can save it as PDF or send it to a printer.

# 8. The final command line

pandoc -s -S -t revealjs --mathjax="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"  -V theme=blood --css test.css -o test.html test.md


# Kneat tricks

So I have finally switched to knitr for doing my vignettes. The result is satisfactory, but the process was not entirely painless.

• The command to run instead of “R CMD Sweave foo.Rnw” is

Rscript -e 'rmarkdown::render("foo.rmd")'

• I think that the concept of writing a package which has the main purpose to generate documentation in literate programming without providing mandatory documentation (such as list of options) within the package itself, referring instead to the online resources is beautifully subversive.

• Knitr in the current R version requires pandoc X.Y.Z, while Ubuntu has X.Y.(Z-1). It was necessary to download the deb package from the pandoc site and install it manually.

• To use knitr in vignettes, you need to add VignetteBuilder:knitr to your DESCRIPTION file.

• I was confused at first as to what to do the old vignette header (the lines that start with “%\Vignette…”). The markdown header is different. Turns out you have to include these lines in the markdown header (Kill me, but I have no idea why there is a “>” behind “vignette:” or “|” behind “abstract:”. Knitr produces neat results, but it is one of the most confusing packages I have ever encountered.):

                ---
title: "FOO: the fooly of foology"
author: "January Weiner"
date: "r Sys.Date()"
output:
pdf_document:
vignette: >
%\VignetteIndexEntry{Foo}
%\VignetteKeyword{foo}
%\VignetteKeyword{foology}
%\VignetteEngine{knitr::rmarkdown}
%\SweaveUTF8
\usepackage[utf8](inputenc)
abstract: |
Foo foo foo foo. Foo foo, foo foo foo, foo.
toc: yes
bibliography: bibliography.bib
---


• <>= becomes {r label, fig.width=5, fig.height=5}. Also, any character argument to options must be in quotes.

• I have no idea why fig.width=5 works, but opt.chunk$set(fig.width=5) doesn’t and at this point I don’t care to ask. • I had a nightmarish forensic experience trying to figure out why my figures don’t get updated, where is the cache and some other things. Turns out that if you provide a symbolic link to an rmd file to knitr, it will change to the directory to where the original is. Which is not the same behavior as in the case of Sweave. • It turns out that some options are valid for HTML, but not PDF, and vice versa, and you don’t get a warning. Also, it’s not mentioned in the documentation. Why? Because f— you, that’s why. For example, I spent half an hour trying to change the theme of a PDF vignette, after which it turned out that the theme option is not valid for PDFs. There was a table somewhere showing which options can be used when, but I lost the link and can’t find it in the documentation. • I haven’t found out how to change the font size if generating pdf_document (my favorite). Update: I have found out that it is not possible. • Also, no idea how to prevent breaking code small chunks between pages, which really, really should not happen. • At first I specified the vignette engine to be knitr::knitr, but apparently this produces only (botched) HTML vignette (botched: no title, no author, no references). To generate neat, honest-to-Knuth PDF via pandoc and LaTeX, one should use knitr::rmarkdown, although that is not documented anywhere. %\VignetteEngine{knitr::rmarkdown} # pandoc, markdown and pander Pandoc + markdown seem to be a great way of documenting my work. Markdown syntax is very simple and allows to add basic formatting and figures to an otherwise simple text document, without obfuscating the actual text. Then I simply compile the document using the pandoc command: pandoc -o document.docx document.md pandoc -o document.pdf document.md  There are some more tricks, of course, and plenty of output formats are possible. One thing I was struggling with was that images in docx files were much too large. It turns out that the PNG graphics I generate from PDFs (which, in turn, come from R) lacked the information about density units. I was using the convert program from ImageMagick, and it turns out it is necessary to add the option -units PixelsPerInch: convert -density 300 -units PixelsPerInch image.pdf image.png  Another thing that I found useful was the pander package. Of course, there is this whole science of generating dynamic documents and reports from R using Sweave or knittr, but at the moment I rather produce two files: a commented R pipeline and, separately, a report in markdown format. (The reason for not using knittr is that I given that I work with some very large data sets that sometimes take ages to compute, I would have to work out the details of cacheing and handling code that takes a while to execute. Also, I want to have a document with all commands, for me, and report without any R code for everyone else). Pander allows to create nice tables in R that can be directly copied and pasted to a markdown document (of course, pander is so much more, but this is my main use at the moment): pander(foo, emphasize.strong.cols=1, justify="left", style="simple", digits=2, split.tables=Inf)  I was astonished how nice the resulting word file is. The PDFs, which are produced by TeX/LaTeX, I think, are actually more trouble, for example because LaTeX disregards my order of figures and tables, they are all floating objects and there is no easy way to change this from within the document. # Creating a graph with variable edge width in Rgraphviz This was waaaaay more complicated than necessary. Figuring it out took me almost a whole day. In essence, there is the graph package in R, which provides graph objects and methods, and there is the Rgraphviz package, which allows you to plot the graphs on the screen. They work well. library(graph) library(Rgraphviz) nodes <- c( LETTERS[1:3] ) edgesL <- list( A=c("B", "C"), B=c("A", "C"), C=c("B", "A" ) ) graph <- new( "graphNEL", nodes= nodes, edgemode="undirected", edgeL=edgesL ) rag <- agopen( graph, "" ) plot(rag)  Here the output: So far, so good. If I wanted to color the edge from A to C red, here is what I could do: eAttrs <- list( color=c( "A~C"="red" ) ) rag <- agopen( graph, "", edgeAttrs=eAttrs ) plot(rag)  The attribute “color” works well. The man page for AgEdge gives us other attributes, specifically, “lwd” which specifies the width of the edge. However, it is not possible to set the edge widths using the above method. I found that the following code works for me: setEdgeAttr <- function( graph, attribute, value, ID1, ID2 ) { idfunc <- function(x) paste0( sort(x), collapse="~" ) all.ids <- sapply( AgEdge(graph), function(e) idfunc( c( attr(e, "head"), attr( e, "tail" )))) sel.ids <- apply(cbind( ID1, ID2 ), 1, idfunc ) if(!all(sel.ids %in% all.ids)) stop( "only existing edges, please" ) sel <- match( sel.ids, all.ids ) for(i in 1:length(sel)) { attr( attr( graph, "AgEdge" )[[ sel[i] ]], attribute ) <- value[i] } return(graph) }  Example: rag <- agopen( graph, "" ) rag <- setEdgeAttr( rag, "lwd", c(5, 20), c("B", "B"), c( "A", "C" ) ) plot(rag)  What a colossal waste of my time. However, I need a visualization with graphs; and it needs to take a custom node drawing function as an argument, so there. # Adding authentication to a shiny server Umph, that was a tough one. I spent ages figuring out how to do it correctly. I have a server running apache (on port 80) and shiny on port (say) 11111. Shiny has its own document root, and within this root, we have a shiny app, say, “example”. So to view this app you need to type http://server:1111/example/. So far, so good. What I wanted, though, was (i) some kind of password protection for the app, and (ii) calling the app from the URL http://server/example/. Turns out it can be done, but it was not trvial. First, I modified configuration of the shiny server to listen only to the specified port and only to the localhost; this prevents anyone from any other machine to connect to shiny: server { listen 11111 127.0.0.1; location / { site_dir /srv/shiny-server; log_dir /var/log/shiny-server; directory_index off; } }  Now to apache. In the httpd.conf file, I have added The following:  <VirtualHost *:80> Redirect /example /example/ ProxyPass /example/ http://127.0.0.1:11111/example/ ProxyPassReverse /example/ http://127.0.0.1:11111/example/ <Location /example> AuthType Basic AuthName "Enter your login name and password" AuthUserFile /etc/httpd/htpasswd.users Require valid-user </Location> </VirtualHost>  This makes apache work as a proxy to the shiny server; however, with the added benefit of a simple authentication for the shiny contents. It took me quite some time to figure out that without the Redirect directive above, http://server/example/ works, but http://server/example (without the slash) doesn’t. Finally, I created new users with htpasswd. Update: Interestingly, shiny cannot handle HEAD requests. HEAD request is when a program asks whether a page is there rather than downloading the whole page. Apparently, this is how CRAN checks whether a site is available. In any case, just after the Virtualhosts directive, I have added the following:  RewriteEngine on RewriteCond %{REQUEST_METHOD} ^HEAD RewriteRule ^/example(.*) /foo/index.html  This rewrites the requested URL to example only if the request method is HEAD, and instead asking the shiny server, it asks itself — and since the file /foo/index.html exists, we get 200 OK. Update 2: I found why shiny is returning 404 to HEAD requests. In the file shiny/R/server.R, in line 177, you have the statement  if (!identical(req$REQUEST_METHOD, 'GET'))
return(NULL)


Obviously, any request other than “GET” gets turned down, as NULL results in a 404.

As a workaround, I have changed it to

  if(identical(req$REQUEST_METHOD, 'HEAD')) return(httpResponse(200, content="OK")) if (!identical(req$REQUEST_METHOD, 'GET'))
return(NULL)


Of course, the down side is that it replies with “OK” even if the given resource does not exist. I am testing a proper way of handling these requests, but at the moment this will have to do.

# tagcloud: creating tag / word clouds

May I present my new package: tagcloud. Tag clouds is for creating, um, tag clouds (aka word clouds). It is based on the code from the wordcloud package, but (i) has no tools for analysing word frequencies, instead (ii) focuses on doing better tag clouds. As to (ii), it adapts to the geometry of the window better and can produce different layouts. Also, with the extrafont package, it can use just any fonts you can think of:

The general syntax is simple. The function tagcloud takes one mandatory argument, the tags to display — a character vector. In the example below, I use the font names available through the extrafont package¹, but it can be anything.

library( extrafont )
tags <- sample( fonts(), 50 )
tagcloud( tags )
dev.copy2pdf( file= "sample1.pdf", out.type= "cairo" )


Note the use of cairo in the above, otherwise the PDF does not include the fonts and the result is not impressive. Here is the result:

OK, let’s add some weights and colors. Also, wouldn’t it be cool if each font name was displayed in the actual font?

weights <- rgamma( 50, 1 )
colors <- colorRampPalette( brewer.pal( 12, "Paired" ) )( 50 )
tagcloud( tags, weights= weights, col= colors, family= tags )


How about mixed vertical and horizontal tags?

tagcloud( tags, weights= weights, col= colors, family= tags,
fvert= 0.5 )


The fvert parameter specifies the proportion of tags that should be displayed vertically rather than horizontally.

Or a different layout?

tagcloud( tags, weights= weights, col= colors,
family= tags, algorithm= "fill" )


Tagclouds comes with additional tools. Firstly, you have editor.tagcloud — a very minimalistic interactive editor. You need to store the object invisibly returned from tagcloud:

tc <- tagcloud( tags, weights= weights, col= colors, family= tags )
tc2 <- editor.tagcloud( tc )
plot( tc2 )


With strmultline you can break up long, multi-word tags into multi-line tags:

tagcloud( strmultline( tags ), weights= weights, col= colors, family= tags )


The result is as follows (notice “Andale Mono” or “DejaVu Sans Light”):

Finally, smoothPalette makes it easy to generate a gradient from numbers. Imagine that we want to code some other numeric information (this could be a p-value, for example) with a smooth gradient from light grey (low value) to black (high value):

newvar <- runif( 50 )
colors2 <- smoothPalette( newvar )
tagcloud( tags, weights=weights, col=colors2, family= tags )


By default, smoothPalette uses a grey-white gradient, but it can actually use any kind of color palette.

1: In order to use the fonts installed on your system, you need to import them — preferably as root — using the extrafont package. At least in my Ubuntu installation you should provide the paths to where your TTF fonts are installed, for example:

library( extrafont )
font_import( paths= "/usr/share/fonts/truetype/" )