Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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:
- A copy of the minimist.js library in the package
inst
dir - Two lines of standard code to initiate the V8 engine and read minimist when loading the R package
- A one-line wrapper function to call the JavaScript function from R
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.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.