如何与来自 R 的孩子一起写入 json [英] How to write to json with children from R
问题描述
我想将 R data.frame 转换为 JSON 对象,以便使用它来准备 d3.js 的数据可视化.我发现了很多关于如何将 JSON 导入 R 的问题,但很少有关于如何将数据从 R 写入 JSON 的问题.
I want to turn an R data.frame into a JSON object in order to use it for preparing data visualizations with d3.js. I found a lot of questions that asked how to get JSON into R, but very few on how to write data from R to JSON.
一个特殊的问题是 JSON 文件需要使用因子嵌套,即 data.frame 的列.我认为从嵌套列表写入可能是一种解决方案,但我已经无法从 data.frame 创建嵌套列表:(
A particular problem is that the JSON file needs to be nested by using factors, i.e. columns of the data.frame. I think that writing from nested lists could be a solution, but I already failed to create a nested list from a data.frame :(
我已经准备了一个例子:
I have preprared an example:
这代表我的 data.frame(称为MyData").
this represents my data.frame (called "MyData").
ID Location Station Size Percentage
1 Alpha Zeta Big 0.63
2 Alpha Zeta Medium 0.43
3 Alpha Zeta small 0.47
4 Alpha Yota Big 0.85
5 Alpha Yota Medium 0.19
6 Alpha Yota small 0.89
7 Beta Theta Big 0.09
8 Beta Theta Medium 0.33
9 Beta Theta small 0.79
10 Beta Meta Big 0.89
11 Beta Meta Medium 0.71
12 Beta Meta small 0.59
现在,我想把它变成这样的有效 json 格式,包括子节点:
now, I want to turn it into something like this valid json format, including the children nodes:
{
"name":"MyData",
"children":[
{
"name":"Alpha",
"children":[
{
"name":"Zeta",
"children":[
{
"name":"Big",
"Percentage":0.63
},
{
"name":"Medium",
"Percentage":0.43
},
{
"name":"Small",
"Percentage":0.47
}
]
},
{
"name":"Yota",
"children":[
{
"name":"Big",
"Percentage":0.85
},
{
"name":"Medium",
"Percentage":0.19
},
{
"name":"Small",
"Percentage":0.89
}
]
}
]
},
{
"name":"Zeta",
"children":[
{
"name":"Big",
"Percentage":0.63
},
{
"name":"Medium",
"Percentage":0.43
},
{
"name":"Small",
"Percentage":0.47
}
]
},
{
"name":"Yota",
"children":[
{
"name":"Big",
"Percentage":0.85
},
{
"name":"Medium",
"Percentage":0.19
},
{
"name":"Small",
"Percentage":0.89
}
]
}
]
}
如果有人可以帮助我,我将非常感激!谢谢
If anyone could help me out I would be very much grateful! thank you
推荐答案
这是一种更简洁的递归方法:
This is a recursive approach which is cleaner:
require(RJSONIO)
makeList<-function(x){
if(ncol(x)>2){
listSplit<-split(x[-1],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],Percentage=x[,2][y])})
}
}
jsonOut<-toJSON(list(name="MyData",children=makeList(MyData[-1])))
cat(jsonOut)
这篇关于如何与来自 R 的孩子一起写入 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!