block by timelyportfolio 94ee6597c6adccef337a

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 ) )

code.R