Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Last active September 6, 2015 12:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timelyportfolio/94ee6597c6adccef337a to your computer and use it in GitHub Desktop.
Save timelyportfolio/94ee6597c6adccef337a to your computer and use it in GitHub Desktop.
use underscore.nest with V8 in R to feed networkD3

underscore.nest | Helpful Tool

A couple years ago, Irene Ros made this handy underscore.nest to create the somewhat tricky nested format to work with many of the the d3.js network layouts. Now, with htmlwidgets, these tricky nested structures are increasingly needed but unfortunately are even more difficult to create in R. V8 from Jeroen Ooms lets us use underscore.nest directly in R.

Example with networkD3 and Titanic

# use https://github.com/iros/underscore.nest in R with V8

library(V8)
# if want hierNetwork use this branch of networkD3 not yet pulled
# devtools::install_github("timelyportfolio/networkD3@feature/d3.chart.layout")
library(networkD3)

ct = new_context()

ct$source(system.file("js/underscore.js", package="V8"))
ct$source("https://raw.githubusercontent.com/iros/underscore.nest/master/underscore.nest.min.js")

ct$eval(sprintf(
  "
    var data = %s;
    JSON.stringify(_.nest(data, %s));
  "
  , jsonlite::toJSON( data.frame(Titanic) )
  , jsonlite::toJSON( names(dimnames(Titanic) ) )
)) %>>%
  (hierNetwork( rjson::fromJSON(.), zoomable = T, collapsible = T ) )
# use https://github.com/iros/underscore.nest in R with V8
library(V8)
# if want hierNetwork use this branch of networkD3 not yet pulled
# devtools::install_github("timelyportfolio/networkD3@feature/d3.chart.layout")
library(networkD3)
ct = new_context()
ct$source(system.file("js/underscore.js", package="V8"))
ct$source("https://raw.githubusercontent.com/iros/underscore.nest/master/underscore.nest.min.js")
ct$eval(sprintf(
"
var data = %s;
JSON.stringify(_.nest(data, %s));
"
, jsonlite::toJSON( data.frame(Titanic) )
, jsonlite::toJSON( names(dimnames(Titanic) ) )
)) %>>%
(hierNetwork( rjson::fromJSON(.), zoomable = T, collapsible = T ) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment