感谢以下问题: Converting toJson R object into a format that fits d3.js tree layout
我有这个很棒的代码,可以为d3.js创建一个Json文件(见下文)
我知道如何从ctree
中提取分割点,如下所示:
library(party)
irisct <- ctree(Species ~ .,data = iris)
我只是不知道如何在以下代码中实现它:
#convert to Json that fits to d3.js layout####
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),
criteria=attr(psplit$splitpoint, "levels"),
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),
"prediction",toString(paste("",toString(round(prediction,3)),"",sep=" ")),
# "criteria split",paste((attr(toString(psplit$splitpoint,levels)))),
sep = " ")
)
)
}
toJSON(get_ctree_parts(irisct))
输出:
{"name":["1"],"criteria":{},"children":[{"name":["2 weights 50 prediction 1, 0, 0 "]},{"name":["3"],"criteria":{},"children":[{"name":["4"],"criteria":{},"children":[{"name":["5 weights 46 prediction 0, 0.978, 0.022 "]},{"name":["6 weights 8 prediction 0, 0.5, 0.5 "]}]},{"name":["7 weights 46 prediction 0, 0.022, 0.978 "]}]}]}
请注意&#34;标准&#34;留空:{}
,而我希望它们充满所有级别。
任何帮助都会很棒!
答案 0 :(得分:0)
我最终通过夹板节点得到了信息:
#convert to Json that fits to d3.js layout####
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),
variableNames=toString(x$psplit$variableName),
criteria=toString(attributes(x$psplit$splitpoint)),
# split = paste(attributes(get_ctree_parts(x$left$psplit$splitpoint)),attributes(get_ctree_parts(x$right$psplit$splitpoint))),
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),
"prediction",toString(paste("",toString(round(prediction,3)),"",sep=" ")),
# "criteria split",paste((attr(toString(psplit$splitpoint,levels)))),
sep = " ")
)
)
}