将嵌套的 JSON 转换为 R 中的转换数据帧

时间:2021-03-26 09:50:36

标签: r dataframe

我有一个关于数据的特定 Json 文件。我想将其转换为数据框并应用一些转换。这是 Json:

{
  "OuterVariable1": [
    {
      "InnerData": "car",
      "InnerList": {
        "wheels": {
          "cost-taxed": 231,
          "cost": 850
        },
        "engine": {
          "cost-taxed": 108,
          "cost": 286
        }
      }
    },
    {
      "InnerData": "van",
      "InnerList": {
        "frame": {
          "cost-taxed": 302,
          "cost": 250
        }
      }
    }, 
   ],

  "OuterVariable2": [
     {
      "InnerData": "truck",
      "InnerList": {
        "wheels": {
          "cost": 1400
        },
      }
    },
  ],
   ...
}

这就是我想要的。请注意 OuterVariable 是一个新列,我们将每个 InnerList 的条目分开。

<头>
外部变量 内部数据 内部列表 成本
外部变量1 “汽车” “轮子” 850
外部变量1 “汽车” “引擎” 286
外部变量1 “面包车” “框架” 250
外部变量2 “卡车” “轮子” 1400

我怎样才能做到这一点?我已经使用 jsonlite 获取初始 DataFrame 并尝试使用 lapply 进行一些转换,但没有运气。

1 个答案:

答案 0 :(得分:1)

我使用 rjson 包而不是 jsonlite 解决了它,因为后者似乎出于某种原因将 year 属性与其余数据分开处理。

我使用了嵌套的 lapply 方法,不确定它在较大的 JSON 数据上的表现如何,但它可以胜任:

library(rjson)
l <- fromJSON(json)

# Loop across each state (use index so we can keep track of the state name)
df_list <- lapply(seq_along(l),
                  function(i) {
                    # inner loop over every year entry
                    inner_list <- lapply(l[[i]], function(y) {
                      data.frame(OuterVariable = names(l)[i],
                                 InnerData = y$InnerData,
                                 InnerList = names(y$InnerList),
                                 Cost = sapply(y$InnerList, "[[", 1),
                    })
                    
                    # Bind together each "mini data.frame" to one per outerVariable
                    do.call("rbind", c(inner_list, make.row.names = FALSE))
                  })

# Bind together the per-outerVariable data.frames
df_result <- do.call("rbind", df_list)

其中 json 是您在上面提供的示例数据。

相关问题