我正在尝试处理一些JSON格式的数据。rjson::fromJSON成功地导入了数据,并将其放入一个相当笨重的列表中。
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形式出现。经过多次尝试和错误,我得到了以下结果:
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但这个命令似乎过于繁琐和复杂。有没有更简单的方法来做这件事?
发布于 2013-07-16 19:28:11
我不确定它是否更简单,但结果更完整,我认为更容易阅读。我使用Map的想法是,对于每对夫妇(年份,细分),将细分数据聚合到单个表中,然后将其与年份合并。
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发布于 2013-07-16 20:19:32
在这里我恢复了列表的几何形状
ni <- seq_along(y[[3]])
nj <- seq_along(y[[c(3, 1, 2)]])
nij <- as.matrix(expand.grid(3, ni=ni, 2, nj=nj))然后,使用nij的行作为索引将相关变量信息提取到嵌套列表中
data <- apply(nij, 1, function(ij) y[[ij]])
year <- apply(cbind(nij[,1:2], 1), 1, function(ij) y[[ij]])并使其成为一个更友好的结构
> data.frame(year, do.call(rbind, data))
year code name employment
1 2014 1 London 74909.59
2 2015 5 West Midlands (England) 69132.34
3 2016 12 Northern Ireland 24313.94
4 2017 5 West Midlands (England) 71723.4
5 2018 9 North East (England) 27199.99
6 2019 4 South West (England) 71219.51https://stackoverflow.com/questions/17674623
复制相似问题