1

有两个数据框

最终数据2:

      id type lang div
1   hola page   es   1

路径:

  source target count
1   hola  adios     1

我可以使用jsonlite以下代码将两个数据帧组合在同一个 JSON 中:

cat(toJSON(c(apply(final_data2,1,function(x)list(id = unname(x[1]), 
type = unname(x[2]), lang = unname(x[3]), div = unname(x[4]))),
apply(paths,1,function(x)list(source = unname(x[1]), target = unname(x[2]),
playcount = unname(x[3])))), pretty = TRUE))

结果是一组数组,如下所示:

[
  {
    "id": ["hola"],
    "type": ["page"],
    "lang": ["es"],
    "div": ["1"]
  },
  {
    "source": ["hola"],
    "target": ["adios"],
    "playcount": ["1"]
  }
]

但是,我需要生成的对象包含两个名称(nodeslinks),每个名称都嵌套一个先前定义的数据框。因此,结构应如下所示:

{
  "nodes": [
    {
        "id": ["hola"],
        "type": ["page"],
        "lang": ["es"],
        "div": ["1"]
    }
  ],
  "links": [
    {
        "source": ["hola"],
        "target": ["adios"],
        "playcount": ["1"]
    }
  ]
}

关于如何实现它的任何提示?

4

1 回答 1

1

只需将 data.frames 作为命名列表传递到toJSON

library(jsonlite)

df1 <- read.table(textConnection("      id type lang div
1   hola page   es   1"), header = T)
df2 <- read.table(textConnection("  source target count
1   hola  adios     1"), header = T)


toJSON(list(nodes = df1, links = df2), pretty = T)
# {
# "nodes": [
#   {
#     "id": "hola",
#     "type": "page",
#     "lang": "es",
#     "div": 1
#   }
#   ],
# "links": [
#   {
#     "source": "hola",
#     "target": "adios",
#     "count": 1
#   }
#   ]
# } 
于 2016-02-17T21:30:51.940 回答