使用rjson处理JSON [英] Processing JSON using rjson
问题描述
我正在尝试处理JSON格式的一些数据. rjson::fromJSON
成功导入数据并将其放入一个笨拙的列表中.
I'm trying to process some data in JSON format. rjson::fromJSON
imports the data successfully and places it into a quite unwieldy list.
library(rjson)
y <- fromJSON(file="http://api.lmiforall.org.uk/api/v1/wf/predict/breakdown/region?soc=6145&minYear=2014&maxYear=2020")
str(y)
List of 3
$ soc : num 6145
$ breakdown : chr "region"
$ predictedEmployment:List of 7
..$ :List of 2
.. ..$ year : num 2014
.. ..$ breakdown:List of 12
.. .. ..$ :List of 3
.. .. .. ..$ code : num 1
.. .. .. ..$ name : chr "London"
.. .. .. ..$ employment: num 74910
.. .. ..$ :List of 3
.. .. .. ..$ code : num 7
.. .. .. ..$ name : chr "Yorkshire and the Humber"
.. .. .. ..$ employment: num 61132
...
但是,由于这本质上是表格数据,因此我希望在简洁的data.frame
中使用它.经过反复尝试,我得到了结果:
However, as this is essentially tabular data, I would like it in a succinct data.frame
. After much trial and error I have the result:
y.p <- do.call(rbind,lapply(y[[3]], function(p) cbind(p$year,do.call(rbind,lapply(p$breakdown, function(q) data.frame(q$name,q$employment,stringsAsFactors=F))))))
head(y.p)
p$year q.name q.employment
1 2014 London 74909.59
2 2014 Yorkshire and the Humber 61131.62
3 2014 South West (England) 65833.57
4 2014 Wales 33002.64
5 2014 West Midlands (England) 68695.34
6 2014 South East (England) 98407.36
但是该命令似乎过于复杂和复杂.有更简单的方法吗?
But the command seems overly fiddly and complex. Is there a simpler way of doing this?
推荐答案
我不确定它是否更简单,但是结果是否更完整,我认为更容易阅读.我使用Map
的想法是,对于每对夫妇(年份,细目分类),将细目分类数据汇总到单个表中,然后将其与年份合并.
I am not sure it is simpler, but the result is more complete and I think is easier to read. My idea using Map
is, for each couple (year,breakdown), aggregate breakdown data into single table and then combine it with year.
dat <- y[[3]]
res <- Map(function(x,y)data.frame(year=y,
do.call(rbind,lapply(x,as.data.frame))),
lapply(dat,'[[','breakdown'),
lapply(dat,'[[','year'))
## transform the list to a big data.frame
do.call(rbind,res)
year code name employment
1 2014 1 London 74909.59
2 2014 7 Yorkshire and the Humber 61131.62
3 2014 4 South West (England) 65833.57
4 2014 10 Wales 33002.64
5 2014 5 West Midlands (England) 68695.34
6 2014 2 South East (England) 98407.36
这篇关于使用rjson处理JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!