gpt4 book ai didi

json - 将 JSON 嵌套到 R 中的数据帧

转载 作者:行者123 更新时间:2023-12-04 18:32:09 25 4
gpt4 key购买 nike

我有一个嵌套的 JSON 文件,具有以下结构:

{"category1": {"town1": 8,"town2": 2},"category2": {"town1": 4,"town2": 3}}

我想将 JSON 导入到 R 中,结构如下:
categories  towns   number
category1 town1 8
category1 town2 2
category2 town1 4
category2 town2 3

我尝试过 fromJSON,也使用 Flatten = TRUE,但这并没有给我我想要的。我可以在 R 中做什么来获得我想要的结构?

最佳答案

诀窍是使用 stack :

library(jsonlite)
lst = fromJSON(json)
transform(stack(lst), towns=c(sapply(lst, names)))

# values ind towns
#1 8 category1 town1
#2 2 category1 town2
#3 4 category2 town1
#4 3 category2 town2

使用 plyr ,一个简洁的类轮是:
library(plyr)
ldply(fromJSON(json), stack)

数据:
json = '{"category1": {"town1": 8,"town2": 2},"category2": {"town1": 4,"town2": 3}}'

关于json - 将 JSON 嵌套到 R 中的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34179122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com