【发布时间】:2016-02-17 05:47:15
【问题描述】:
这是来自Converting ctree output into JSON Format (for D3 tree layout)的后续问题
我有以下代码,使用ctree 生成(来自Party,请参见下面生成它的代码),我的目的是创建一个递归函数来转换以下 Json 输出:
{"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]}}}
如下:
{ "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]",
}
]
}
这让我可以创建以下精彩的d3.js 输出:
背景:
我有以下创建 Json 输出的代码,但没有退出我需要的代码:
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))
我尝试对其进行改造,但似乎我遇到了一些挑战,我无法解决: 为了得到一个通用的解决方案,我需要一些递归函数,它创建一个嵌套的 Json 对象,只要有一个拆分(子),而且,ctree 具有与 d3.js 导航约定不同的导航约定,在 ctree 中导航使用“右”和“左”累积,其中 d3.js 需要“子”导航”
在这方面的任何帮助都会很棒,我坚持要退出一段时间:)
【问题讨论】:
标签: javascript json r