简体   繁体   English

在R中将数据帧转换为JSON

[英]Convert data frame to json in R

I have a data frame df that I'd like to convert to json format: 我有一个要转换为json格式的数据框df

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

The data frame contains index-values (IndexBV) and their standard errors (SE) for two different species (ArtId 50 and 70) for the years 1990-1993. 数据框包含1990-1993年两个不同物种(ArtId 50和70)的索引值(IndexBV)及其标准误差(SE)。

When I do: 当我做:

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

I get this (only the first two elements are shown): 我明白了(仅显示了前两个元素):

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

But what I need as desired.res is a structure that looks as follows when printed with cat(jsonlite::toJSON(desired.res, pretty=T)) : 但我需要尽可能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}
        ]
    }
}

How can I convert df to desired.res ? 如何将df转换为期望的.res I think the problem is about reshaping df into a nested list to take into account its nested structure. 我认为问题在于将df重塑为嵌套列表以考虑其嵌套结构。

I can give a very specific solution, but to generalise will take more work, as its a strange format to me. 我可以给出一个非常具体的解决方案,但是概括起来将需要更多的工作,因为这对我来说是一种奇怪的格式。 Try this out, and adapt to make more robust accordingly eg the year going from length 8 to length 4. 尝试一下,并相应地使其变得更健壮,例如从长度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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM