我想在R中创建一个与D3树结构flare.json对应的不齐列表。我的数据是在data.frame:Ragged list or data frame to JSON
path <- data.frame(P1=c("direct","direct","organic","direct"),
P2=c("direct","direct","end","end"),
P3=c("direct","organic","",""),
P4=c("end","end","",""), size=c(5,12,23,45))
path
P1 P2 P3 P4 size
1 direct direct direct end 5
2 direct direct organic end 12
3 organic end 23
4 direct end 45
,但它也可能是一个列表,或者如果有必要重塑:
path <- list()
path[[1]] <- list(name=c("direct","direct","direct","end"),size=5)
path[[2]] <- list(name=c("direct","direct","organic","end"), size=12)
path[[3]] <- list(name=c("organic", "end"), size=23)
path[[4]] <- list(name=c("direct", "end"), size=45)
所需的输出是:
rl <- list()
rl <- list(name="root", children=list())
rl$children[1] <- list(list(name="direct", children=list()))
rl$children[[1]]$children[1] <- list(list(name="direct", children=list()))
rl$children[[1]]$children[[1]]$children[1] <- list(list(name="direct", children=list()))
rl$children[[1]]$children[[1]]$children[[1]]$children[1] <- list(list(name="end", size=5))
rl$children[[1]]$children[[1]]$children[2] <- list(list(name="organic", children=list()))
rl$children[[1]]$children[[1]]$children[[2]]$children[1] <- list(list(name="end", size=12))
rl$children[[1]]$children[2] <- list(list(name="end", size=23))
rl$children[2] = list(list(name="organic", children=list()))
rl$children[[2]]$children[1] <- list(list(name="end", size=45))
所以,当我打印到JSON它是:
require(RJSONIO)
cat(toJSON(rl, pretty=T))
{
"name" : "root",
"children" : [
{
"name" : "direct",
"children" : [
{
"name" : "direct",
"children" : [
{
"name" : "direct",
"children" : [
{
"name" : "end",
"size" : 5
}
]
},
{
"name" : "organic",
"children" : [
{
"name" : "end",
"size" : 12
}
]
}
]
},
{
"name" : "end",
"size" : 23
}
]
},
{
"name" : "organic",
"children" : [
{
"name" : "end",
"size" : 45
}
]
}
]
}
我是我的头很难绕过在R中创建此列表结构所需的递归步骤。在JS我可以非常容易地在节点周围移动,并且在每个节点确定是添加新节点还是继续向下移动根据需要使用推,例如:或new = {"name": node, "size": size};
,如在此example中那样。我试图split
的data.frame在本example:
makeList<-function(x){
if(ncol(x)>2){
listSplit<-split(x,x[1],drop=T)
lapply(names(listSplit),function(y){list(name=y,children=makeList(listSplit[[y]]))})
} else {
lapply(seq(nrow(x[1])),function(y){list(name=x[,1][y],size=x[,2][y])})
}
}
jsonOut<-toJSON(list(name="root",children=makeList(path)))
,但它给我一个错误
Error: evaluation nested too deeply: infinite recursion/options(expressions=)?
Error during wrapup: evaluation nested too deeply: infinite recursion/options(expressions=)?
什么是您的数据帧是什么样子? – AmeliaBR
@AmeliaBR我添加了数据框的输出。 –
好的。是的,你有那里的信息,但我无法弄清楚它是如何表示树形结构的。现在我看到:每行代表从根到叶的路径。 [这是另一个类似数据结构的d3/javascript示例](http://stackoverflow.com/a/20964688/3128209),我将尝试在R中重新编写它。 – AmeliaBR