Function to source R scripts from Dropbox files

source.dropbox = function(dropbox.url) {

    # Purpose: source an R script from a Dropbox file

    # Input: the URL that you get when you share a Dropbox file

    # Output: the input to the source() function

    # Example of use:
    # source(source.dropbox('https://www.dropbox.com/s/9m4139zbnee59jh/grfpairs.R'))

    # Author: George Fisher george@georgefisher.com

    # Date : October 30, 2013

    # thanks to
    # http://thebiobucket.blogspot.com/2012/05/source-r-script-from-dropbox.html

    # note: this goes out over the network so you might want to package several
    # functions into one file

    library(RCurl)
    setwd(tempdir())

    destfile = "test.txt"

    # use regex to get the piece of the Dropbox URL we need
    matches <- regexpr("(/s/.*)", dropbox.url, perl = TRUE, ignore.case = TRUE)
    result <- attr(matches, "capture.start")[, 1]
    attr(result, "match.length") <- attr(matches, "capture.length")[, 1]
    dropbox.tail = regmatches(dropbox.url, result)
    # (my eternal thanks to the RegexBuddy program)

    # create the request URL
    dburl = paste("https://dl.dropbox.com", dropbox.tail, sep = "")

    x = getBinaryURL(dburl, followlocation = TRUE, ssl.verifypeer = FALSE)
    writeBin(x, destfile, useBytes = TRUE)


    paste(tempdir(), "/test.txt", sep = "")
}

# example output
source.dropbox("https://www.dropbox.com/s/9m4139zbnee59jh/grfpairs.R")
## [1] "C:\\Users\\GRFISH~1\\AppData\\Local\\Temp\\RtmpQBRlTX/test.txt"

Motivation

The Coursera Data Analysis course involves “peer review” of projects and the reviewers need to run other peoples' code (primarily Rmd files) on their computers. Giving them access to user-written functions is therefore important. The suggestion that we include the source code of all our functions at the head of every Rmd file is simply not workable.

At the R console you can simply source the correct URL; but inside an Rmd file you can't. Who knows why, you just can't.

Demonstration

I have a function stored in a Dropbox file named grfpairs.R which produces an improved version of the pairs() function found in base R (with a little help from Winston Chang).

When I get the Dropbox link to it, the URL is

https://www.dropbox.com/s/9m4139zbnee59jh/grfpairs.R

# get the R script from Dropbox

# the sequence of 'ls()' shows that it actually does get the functions
ls()
## [1] "source.dropbox"
source(source.dropbox("https://www.dropbox.com/s/9m4139zbnee59jh/grfpairs.R"))
ls()
## [1] "grfpairs"       "panel.cor"      "panel.hist"     "source.dropbox"

setwd("~/R/regression")

# a data file from the Statistics.com Regression Analysis course
collgpa = read.csv("collgpa.csv")

# a nice analysis of the relevant variables using the grfpairs function I
# just sourced
grfpairs(collgpa[, c("Verb", "Math", "Gpa")], main = "GPA vs. Verbal and Math scores")

plot of chunk unnamed-chunk-2