【问题标题】:Long table to nested list to JSON using R and tidyverse使用 R 和 tidyverse 将长表嵌套到 JSON
【发布时间】:2018-05-21 19:09:53
【问题描述】:

我正在尝试使用 R/tidyverse 和其中一个 JSON 包将长表(例如下面的示例)转换为嵌套列表到 JSON。我怀疑这可以通过某种方式使用 split/purrr 来完成,但我无法弄清楚到底如何。

采取以下示例输入:

library(tidyverse)
library(stringi)

df = data.frame(patient   = c(rep("A",4), rep("B",4)),
                sample    = rep(c("P","R"),4),
                file      = stri_rand_strings(8, 6, '[A-Z]'))

例如看起来像这样

  patient sample   file
1       A      P ZZEVYQ
2       A      R KIUXRU
3       A      P XRYBUE
4       A      R ZCHBKN
5       B      P WZYAPM
6       B      R EKDFYT
7       B      P CYEJCK
8       B      R XFAYXX

我想输出类似的内容(注意:手动输入)。

[
  {
    "patient" : "A",
    "samples" : [
      {
        "sample" : "P",
        "files" : [
          {
            "file" : "ZZEVYQ"
          },
          {
            "file" : "XRYBUE"
          }
        ] 
      },
      {
        "sample" : "R",
        "files" : [
          {
            "file" : "KIUXRU"
          },
          {
            "file" : "ZCHBKN"
          }
        ]
      }
    ]
  },
  {
    "patient" : "B",
    "samples" : [
      {
        "sample" : "P",
        "files" : [
          {
            "file" : "WZYAPM"
          },
          {
            "file" : "CYEJCK"
          }
          ] 
      },
      {
        "sample" : "R",
        "files" : [
          {
            "file" : "EKDFYT"
          },
          {
            "file" : "XFAYXX"
          }
        ]
      }
    ]
  }
]

关于如何做到这一点的任何建议?

非常感谢!

【问题讨论】:

    标签: r json tidyverse


    【解决方案1】:

    对于大多数 json 输出,如果你想要嵌套级别,那么你需要嵌套你的数据。这是实现获取所需 JSON 所需的下一步的一种方法

    dfout <- df %>% group_by(patient, sample) %>% 
      summarize(files=list(map(file, ~list(file=.x)))) %>% 
      summarize(samples=list(map2(sample, files, ~list(samples=.x, files=.y))))
    
    jsonlite::toJSON(dfout, auto_unbox = TRUE)
    

    【讨论】:

    • 有没有办法修改它以允许任意数量的嵌套,例如。 mapN(样本, 文件, ...., n, ...)
    • 你不应该在问题被回答后更改它。如果您有原始帖子未涵盖的问题,最好创建一个新帖子,而不是完全改变问题。此外,新问题更有可能引起注意。
    • 好的,这是新问题...stackoverflow.com/questions/50477156/…
    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 2013-11-19
    相关资源
    最近更新 更多