Interactive JavaScript in R with V8: a crossfilter example

December 24, 2014


In last weeks blog post introducing the new V8 package I showed how you can use context$eval and context$source to execute commands and scripts of JavaScript in R.

It turns out that typing context$eval() for each JavaScript command gets annoying very quickly, so the new V8 version 0.3 adds an interactive console feature that works very similar to the one in chrome developer tools or Firebug. Playing in the interactive console is a nice way to debug a session, or just to learn JavaScript.

# Load stuff
library(V8)
data(diamonds, package="ggplot2")

# Create JavaScript session
ct <- new_context()
ct$assign("diamonds", diamonds)

# Load CrossFilter JavaScript library
ct$source("http://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.11/crossfilter.min.js")

The code above loads the diamonds dataset from the ggplot2 package and assigns it to a new JavaScript context. We also load the crossfilter JavaScript library. We can now use the console method to enter an interactive JavaScript console for this session:

ct$console()
# This is V8 version 3.14.5.10. Press ESC or CTRL+C to exit.
# ~

The ~ prompt indicates that we are in V8 now and can start typing JavaScript. For example to filter the 10 diamonds with the highest depth in the price range between 2000 and 3000:

//now we are in javasript :)
var cf = crossfilter(diamonds)
var price = cf.dimension(function(x){return x.price})
var depth = cf.dimension(function(x){return x.depth})
price.filter([2000, 3000])
output = depth.top(10)

You’ll notice that crossfilter is pretty fast! To in inspect the data in JavaScript we can convert it to JSON:

JSON.stringify(output)

But easier might be to read the data in R. Exit the prompt by pressing ESC, which gives you back R’s default > prompt. From there we can read the retrieve the output object using ct$get:

# Pressing ESC
# Exiting V8 console.
output <- ct$get("output")
print(output)

All of this will work seamlessly in most editors too. For example if you load this script in RStudio, you can execute it by selecting the code and pressing the Run button in the script editor, and it does exactly what you would expect!

However, the console is of course mostly for debugging and interactive use. If you plan to share your R script, the most elegant way to include some JavaScript code is by putting it in a seperate file myscript.js and then load it from R using ct$source("myscript.js").