This is a followup question from : Converting ctree output into JSON Format (for D3 tree layout)
I have the following code, produced using ctree
(from Party
, see bellow the code that produced it), my intention is to create a recursive function that transforms the following 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]}}}
into the following:
{ "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]",
}
]
}
which lets me create the following wonderful d3.js
output:
Background:
I have the following code which creates a Json output, but not quit the code i need:
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))
I tried to transform it, but it seems like i have a few challenges, i just cant solve: in order to get a general solution, i need some recursive function, that creates a nested Json object, whenever there is a split (children), also, ctree have different navigation conventions from the d3.js navigation convention, where in ctree the navigation accrues using "right" and "left", where d3.js requires "children" navigation"
Any help on this would be wonderful, i'm stuck on this for quit a while :)