Following up from a previous question regarding converting ctree output to JSON format for D3 tree layout, I have the following code generated by the use of ctree (from Party package) and I aim to create a recursive function to transform the JSON output.
{"nodeID":[1],"left":{"nodeID":[2],"weights":[50],"prediction":[1,0,0]},"right":{"nodeID":[3],"left":{"nodeID":[4],"left":{"nodeID":[5],"weights":[46],"prediction":[0,0.9783,0.0217]},"right":{"nodeID":[6],"weights":[8],"prediction":[0,0.5,0.5]}},"right":{"nodeID":[7],"weights":[46],"prediction":[0,0.0217,0.9783]}}}
The desired transformation is as follows:
{"name": "1", "children": [{"name": "3","children":[{"name": "4","children":[{"name":"5 weights:[46] prediction:[0,0.9783,0.0217]"},{"name":"6 weights:[8] prediction[0,0.5,0.5]",
{"nodeID":"7 weights:[46] prediction[0,0.0217,0.9783]"}]},{"name": "2 weights:[50] prediction[1,0,0]"}]}
This transformation enables the creation of a visual representation using d3.js https://i.sstatic.net/fcP5Y.png.
Background:
I currently have code that outputs JSON data but it requires further manipulation:
library(party)
irisct <- ctree(Species ~ .,data = iris)
plot(irisct)
get_ctree_parts <- function(x, ...)
{
UseMethod("get_ctree_parts")
}
get_ctree_parts.BinaryTree <- function(x, ...)
{
get_ctree_parts(attr(x, "tree"))
}
get_ctree_parts.SplittingNode <- function(x, ...)
{
with(
x,
list(
nodeID = nodeID,
left = get_ctree_parts(x$left),
right = get_ctree_parts(x$right)
)
)
}
get_ctree_parts.TerminalNode <- function(x, ...)
{
with(
x,
list(
nodeID = nodeID,
weights = sum(weights),
prediction = prediction
)
)
}
toJSON(get_ctree_parts(irisct))
Efforts to transform this code face challenges in creating a recursive function for nested JSON objects reflecting the splitting nodes while accommodating different navigation conventions between ctree and d3.js.
Any assistance on resolving these challenges would be greatly appreciated!