【发布时间】:2020-11-26 02:07:59
【问题描述】:
我有以下数据框:
fakedat<-data.frame(name=c("Holdingcompany","Holdingcompany","company1","company1","company2","company2"),children=c("company1","company2","company4","company3","company5","company6"),info=c("text1","text2","text3","text5","othertext","other_text"),percentage=c("100%","100%","60%","75%","80%","70%"))
我希望的输出如下:
{"name": "Holdingcompany",
"children": [
{
"name": "company1",
"tooltip": "text1",
"percentage": "100%",
"children": [
{
"name": "company4",
"tooltip": "text3",
"percentage": "60%"
},
{
"name": "company3",
"tooltip": "text5",
"percentage": "75%"
}
]
},
{
"name": "company2",
"tooltip": "text2",
"percentage": "100%",
"children": [
{
"name": "company5",
"tooltip": "othertext",
"percentage": "80%"
},
{
"name": "company6",
"tooltip": "other_text",
"percentage": "70%"
}
]
}
]
}
我尝试了几种不同的解析方法,包括: How to write to json with children from R
但不幸的是,我无法按照我希望的方式将上述代码正确应用于列表中的孩子。
尝试从下面提到的可能重复项中应用一些解决方案,我遇到了递归错误:“C 堆栈使用量太接近限制”,因为函数似乎在调用自身。
##Adding in IDs
fakedat<-data.frame(id=c(1,2,3,4,5,6),name=c("Holdingcompany","Holdingcompany","company1","company1","company2","company2"),
children=c("company1","company2","company4","company3","company5","company6"),
info=c("text1","text2","text3","text5","othertext","other text"),
percentage=c("100%","50%","60%","75%","80%","70%"))
get_node <- function(df, id) {
node <- as.list(df[df$id == id, c("name", "info",
"percentage","id")])
names(node) = c("name", "info", "percentage","id")
id1<-df[df$id==id,]$children
if (!is.na(id1)){
child1 <- get_node(df, id)
if(child1$name == node$name){
node$children <- list(child1)}
node
}
}
jsonlite::toJSON(get_node(fakedat,6), pretty = TRUE, auto_unbox =
TRUE)`
Error: C stack usage 7972496 is too close to the limit
【问题讨论】: