这是来自Converting ctree output into JSON Format (for D3 tree layout)
的后续问题我有以下代码,使用System/libraries/Session/Session.php.
生成(来自ctree
,请参阅产生它的代码),我的目的是创建一个转换以下Json输出的递归函数:
Party
进入以下内容:
{"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]",
}
]
}
输出:
背景:
我有以下代码创建一个Json输出,但不退出我需要的代码:
d3.js
我试图改变它,但似乎我有一些挑战,我只是无法解决: 为了得到一个通用的解决方案,我需要一些递归函数,它创建一个嵌套的Json对象,每当有一个分裂(子)时,ctree也有不同的导航约定来自d3.js导航约定,其中ctree导航累计使用“右”和“左”,其中d3.js需要“儿童”导航“
任何有关这方面的帮助都会很精彩,我会坚持这一步退出一段时间:)
答案 0 :(得分:3)
嗨,我刚刚看到帖子后开始进行R编码,这是我到目前为止实现的。
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(
name = toString(nodeID),
children = list(get_ctree_parts(x$left),get_ctree_parts(x$right))
)
)
}
get_ctree_parts.TerminalNode <- function(x, ...)
{
with(
x,
list(
name = paste(nodeID,"weights",sum(weights),"prediaction",toString(paste("[",toString(prediction),"]",sep=" ")),sep = " ")
)
)
}
toJSON(get_ctree_parts(irisct))
Json输出:
{"name":["1"],"children":[
{"name":["2 weights 50 prediaction [ 1, 0, 0 ]"]},
{"name":["3"],"children":[
{"name":["4"],"children":[
{"name":["5 weights 46 prediaction [ 0, 0.978260869565217, 0.0217391304347826 ]"]},
{"name":["6 weights 8 prediaction [ 0, 0.5, 0.5 ]"]}]
},
{"name":["7 weights 46 prediaction [ 0, 0.0217391304347826, 0.978260869565217 ]"]
}]
}]
}
如果您有任何问题,请尽我所能。