简体   繁体   English

从dataFrame到R中的分组JSON

[英]From dataFrame to grouped JSON in R

I have a data frame in R:我在 R 中有一个数据框:

ID   var1  var2 
1    12    Name1
1    13    Name4
2    13    Name2
3    14    Name3

and i wish to transform in json grouping the ones that have the same ID:我希望在 json 中转换具有相同 ID 的分组:

{
"group":
[
{"ID" : 1, "var1": 12, "var2": "Name1" },
{"ID" : 1, "var1": 13, "var2": "Name4" }
]
},
{
"group":
[
{"ID" : 2, "var1": 13, "var2": "Name2" }
]
},
{
"group":
[
{"ID" : 3, "var1": 14, "var2": "Name3" }
]
}

I also want to save each group on a JSON file, so, for the example above, I will have three JSON files我还想将每个组保存在一个 JSON 文件中,因此,对于上面的示例,我将拥有三个 JSON 文件

But I can't figure out a way to do this, neither to mount the JSON as I want nor to save each group separately on a JSON file.但是我想不出一种方法来做到这一点,既不按我的意愿挂载 JSON,也不将每个组分别保存在 JSON 文件中。

We can use jsonlite我们可以使用jsonlite

library(jsonlite)
library(purrr)
lst1 <-  map(split(df1, df1$ID), toJSON)
names(lst1) <- paste0('group', names(lst1))
toJSON(lst1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM