在R中将数据帧转换为JSON

时间:2019-01-10 11:13:35

标签: r json jsonlite

我有一个数据框 df ,我想将其转换为json格式:

df <- data.frame(`ArtId` = rep(c(50,70),each=4), 
  `Year` = rep(1990:1993,times=2), 
  `IndexBV` = c(132,94,83,101,100,100,67,133), 
  `SE` = c(20,15,12,13,NA,NA,NA,NA))

ArtId Year IndexBV SE
50    1990 132     20
50    1991  94     15
50    1992  83     12
50    1993 101     13
70    1990 100     NA
70    1991 110     NA
70    1992  67     NA
70    1993 133     NA

数据框包含1990-1993年两个不同物种(ArtId 50和70)的索引值(IndexBV)及其标准误差(SE)。

当我这样做时:

cat(jsonlite::toJSON(df, pretty=T))

我明白了(仅显示前两个元素):

[
  {
    "ArtId": 50,
    "Year": 1990,
    "IndexBV": 132,
    "SE": 20
  },
  {
    "ArtId": 50,
    "Year": 1991,
    "IndexBV": 94,
    "SE": 15
  },
... 

但是我所需要的 desired.res 是一个用cat(jsonlite::toJSON(desired.res, pretty=T))打印时看起来如下的结构:

{
    "Year":["1990","1991","1992","1993"],
    "ArtId": {
        "50":[
            {"IndexBV": 132, "SE": 20},
            {"IndexBV": 94, "SE": 15},
            {"IndexBV": 83, "SE": 12},
            {"IndexBV": 101, "SE": 13}
        ],
        "70":[
            {"IndexBV": 100, "SE": NA},
            {"IndexBV": 110, "SE": NA},
            {"IndexBV": 67, "SE": NA,
            {"IndexBV": 133, "SE": NA}
        ]
    }
}

如何将 df 转换为 desired.res ? 我认为问题在于将 df 重塑为嵌套列表以考虑其嵌套结构。

1 个答案:

答案 0 :(得分:0)

我可以给出一个非常具体的解决方案,但是概括起来将需要更多的工作,因为这对我来说是一种奇怪的格式。试试看,并相应地使其变得更强大,例如从长度8到长度4的一年。

# I find data.table easier
library(data.table)
dt <- as.data.table(df)

# manually can do it, find levels of L, split data and name
L <- unique(df$ArtId)
ArtList <- lapply(L, function(x){
  x.dt <- dt[ArtId == x, .(IndexBV, SE)]
  x.dt
})
names(ArtList) <- L

# combine in to one list
X <- list(Year=unique(dt$Year),
          ArtId = ArtList)

# convert to Json, need either "null" or "string" for na, else dropped
jsonlite::toJSON(X, pretty = TRUE, na="null")
相关问题