我有一个嵌套的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
我尝试使用JSON,也使用Flatten = TRUE,但这并没有给我我想要的东西。我可以在R中做什么来获得我想要的结构?
答案 0 :(得分:4)
json <- fromJSON('{"category1": {"town1": 8,"town2": 2},"category2":{"town1": 4,"town2": 3}}')
json <- data.frame(number = unlist(json))
json$rownames <- rownames(json)
rownames(json) <- NULL
json$categories <- lapply(strsplit(as.character(json$rownames), "\\."), "[", 1)
json$town <- lapply(strsplit(as.character(json$rownames), "\\."), "[",2)
json$rownames <- NULL
答案 1 :(得分:4)
诀窍是使用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}}'