From good to bad and back: Convert data.tree to and from list, json, networkD3, and more 4

It is very easy to convert data.tree Nodes to and from list, JSON, networkD3, and other data structures. Examples and more!

The data.tree package provides a facility to create and manage tree structures in R, and to decorate nodes with methods. This comes in handy for many algorithms. For an example, see here. Or read up the vignettes in the package, e.g. from CRAN.
In the last post, I showed how we can write a custom converter to convert a data.tree Node to a JSON string. For standard conversions, this has just become extremely simple. As of today, data.tree contains generic methods to convert a data.tree from and to a list.

Convert a Node to a list

Converting a data.tree Node to a list is really simple:

Alternatively, you might prefer the “traditional” generic method:

Convert a Node to JSON

Conversion to JSON becomes trivial:

The result is (doing some pretty-printing):

If we prefer our children to be in an array, we can use the unname flag. This will cause the nested children elements to be unnamed in the list:

This yields:

There are multiple options in the ToList method. Type the following to learn more:

Namely, you can call the reserved-word “name” and “children” differently when importing and exporting, if you want.

Convert a list to a Node

As a side note: you can also convert a list to a Node:



All this opens endless possibilities for integration with other packages. For example, to draw a tree with the networkD3 package:

The result is here. Not very meaningful, I agree, but you get the idea.

Note that the ToList feature is not yet rolled out to CRAN, but you can easily try it out by downloading it from github:

Next, I’ll be working on converting a data.tree to a dendrogram for plotting, and to a party object (from the partykit package) for access to partinioning algorithms.


The Breaking Bad Walther White transformation image has been created by AznKyuubi and is published under a Creative Commons license.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 thoughts on “From good to bad and back: Convert data.tree to and from list, json, networkD3, and more