block by timelyportfolio c8278237616592474b2a

d3 hierarchies in R

Built with blockbuilder.org

It seems that working with d3.js hierarchies in R causes much consternation. Here is a quick little demonstration of working with the flare.json hierarchy often used in d3, processing, and Protovis. data.tree eases the pain considerably. I also include the purrr code for those interested in this library and/or some hierarchy recursion in R.

loading the data

# work through d3 hierarchies in R
#  using data.tree and dplyr
#  on the commmonly used flare.json

library(jsonlite)
library(data.tree)
library(dplyr)
library(purrr)

# import as a list with jsonlite
flare <- fromJSON(
  "http://bl.ocks.org/mbostock/raw/4063269/flare.json",
  simplifyDataFrame = FALSE
)

# quick and easy from d3 hierarchy list to data.tree
(flare_dtree <- as.Node(flare, mode = "explicit"))

# how might it look as a tbl_df from dplyr
(flare_tbldf <- data_frame(
  fromJSON(
    "http://bl.ocks.org/mbostock/raw/4063269/flare.json",
    simplifyDataFrame = FALSE
  )$children
))

extracting some data

# now let's pull in the size attribute using each library
flare_dtree$Get("size")
flare_dtree$Get("size") %>% stripchart(pch="|",xlab="size")

# little more difficult without data.tree
walk_tree <- function(hierarchy, rootname="root"){
  size_df <- data_frame(name=rootname)

  make_df <- function(l_to_df){
    size = NA
    if("size" %in% names(l_to_df)) size = l_to_df$size
    data_frame(
      "name"=l_to_df$name,
      "size" = size
    )    
  }  

  recurse <- function(l){
    size_df <<- bind_rows(
      size_df,
      map_df(
        l,
        ~{
           make_df(.x)
        }   
      )
    )

    map(
      l,
      ~{
        if("children" %in% names(.x)){
          recurse(.x$children)
        }
      }
    )

  }

  map(hierarchy,recurse)

  size_df
}

walk_tree(flare_tbldf)