RMarkdown is a really simple authoring format that allows one to create dynamic documents from R, mixing code with text. The RPubs service by RStudio makes it really easy to author and publish these documents on the web. My only gripe with RPubs is better articulated by the following tweet exchange.
TLDR; there is no way to upload the source Rmd file along with the HTML, while publishing to RPubs.
@johnmyleswhite BTW, is there any way to download the actual Rmarkdown files from Rpubs? Wanted to try the R version, can't download source.
— Fernando Perez (@fperez_org) April 5, 2014
@johnmyleswhite ah, ok. It seemed like it should be an obvious feature, but nope… Or at least I can't find a way.
— Fernando Perez (@fperez_org) April 5, 2014
This got me thinking if there was a simple solution to this problem so that the source Rmd file coule be included while publishing to Rpubs, making it is easy for people to share their analyses in a reproducible fashion. After a few experiments, I finally came up with a solution that makes use of DataURIs. Here is the basic idea.
Our first step is to convert the contents of the Rmd file into a base64 encoded data URI. Thanks to the base64enc package, this can be done in a single line of code
myrmd = base64enc::dataURI(file = "mynb.Rmd", mime = "text/rmd")
The next step is to add a download link to the page. We can make it pretty by using some font icons.
cat(sprintf("\n <a href='%s' target='_blank' download='mynb.Rmd'>\n <span class='glyphicon glyphicon-cloud-download' style='font-size:1.2em;'></span> Download\n </a>",
myrmd))
Let us wrap this up into a function so that it can be reused easily
add_download_link = function(file) {
myrmd = base64enc::dataURI(file = file, mime = "text/rmd")
dl_link = "<a href='%s' target='_blank' download='mynb.Rmd'>\n <span class='glyphicon glyphicon-cloud-download' style='font-size:1.2em;'></span> \n Download\n </a>"
cat(sprintf(dl_link, myrmd))
}
This solution probably won't work with all browsers, since DataURI support is not universal. However, it is still a good starting point IMHO. It would be nice if this feature could be auto-enabled so that all docs shared on Rpubs have a source!