Minimist: an example of writing native JavaScript bindings in R

February 15, 2015
By

(This article was first published on OpenCPU, and kindly contributed to R-bloggers)

opencpu logo

A new package has appeared on CRAN called minimist, which implements an interface to the popular JavaScript library. This package has only one function, used for argument parsing. For example in RGui on OSX, the output of commandArgs() looks like this:

> commandArgs()
[1] "R"                 "--no-save"         "--no-restore-data" "--gui=aqua"

Minimist turns that into this:

> library(minimist)
> minimist(commandArgs())
$`_`
[1] "R"

$save
[1] FALSE

$`restore-data`
[1] FALSE

$gui
[1] "aqua"

Note how it interprets the --no- prefix as FALSE and the --foo=bar as a key-value pair. It has some more of these rules, following the usual scripting argument syntax conventions. Cool, but not exactly ground breaking; there are already half a dozen packages on CRAN for parsing arguments (although this one is particularly nice :P).

Writing JavaScript bindings using V8

The main purpose of this new package is to exemplify how to write a package with bindings to a JavaScript library using V8. If you take a look at the package source, you might be surprised how small it is. The package consists of:

That’s it. To install this package from source no compiler is required. It will build out of the box, even on machines without Rtools or Xcode. Moreover, there are no external dependencies as is the case for e.g. Java code, where we need to install a JVM. Everything is self contained within R and V8. It’s fast too:

> system.time(minimist(commandArgs()))
   user  system elapsed 
  0.001   0.000   0.001

I’m working on several other packages to implement bindings to cool JavaScript libraries (see also yesterdays post). If you have some suggetions for other JavaScript libraries that might be useful in R, get in touch.

To leave a comment for the author, please follow the link and comment on their blog: OpenCPU.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)