我在R中有我的JSON文件“ json”的子集
library(jsonlite)
json <- '{"year": {"2015":{"id": 10, "number": 1, "amount": 5},"2016": {"id": 2, "number": 6, "amount": 9}}}'
data1 <- jsonlite::fromJSON(json)
v<-as.data.frame(data1)
v
看起来像这样
year.2015.id year.2015.number year.2015.amount year.2016.id year.2016.number year.2016.amount
1 10 1 5 2 6 9
但是我只想要最后一个具有变量“ id”,“ number”,“ amount”的对象。因此所需的输出将是这样。
id number amount
10 1 5
2 6 9
当嵌套json文件时,我只想查看级别,该级别的数据具有可变ID年和数字,而不是带有Year的级别。
最好的问候,ChristianSkjøth
当您将数据框列表的列表自动转换为数据框时,会发生此问题,您需要的是访问数据框data1 $ year而不是data1的列表,然后绑定数据。
library(jsonlite)
json <-
'{"year": {"2015":{"id": 10, "number": 1, "amount": 5},"2016": {"id": 2, "number": 6, "amount": 9}}}'
data1 <- jsonlite::fromJSON(json)
do.call("rbind", data1$year)
# id number amount
# 2015 10 1 5
# 2016 2 6 9
dplyr::bind_rows(data1$year, .id = NULL)
# # A tibble: 2 x 3
# id number amount
# <int> <int> <int>
# 10 1 5
# 2 6 9
plyr::ldply(data1$year, data.frame, .id = NULL)
# # A tibble: 2 x 3
# id number amount
# <int> <int> <int>
# 10 1 5
# 2 6 9
您可以使用library(jqr)
子集化json本身,然后在提取所需的值之后构建data.frame
library(jqr)