在 R 中将数据框转换为 json

Convert data frame to json in R

我有一个数据框 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 重塑为嵌套列表以考虑其嵌套结构。

我可以给出一个非常具体的解决方案,但概括起来需要更多的工作,因为它对我来说是一种奇怪的格式。尝试一下,并相应地进行调整以使其更强大,例如从长度 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")