我的数据框如下:
item <- c(rep.int("Item ID 1", 4), rep.int("Item ID 2", 3))
links <- c("A", "B", "C", "D", "A", "E", "F")
df <- as.data.frame(cbind(item, links))
我希望将此转换为json
,每个links
键都有多个值(这是正确的术语吗?)
预期的JSON
{
"items": [
{
"type": "item",
"name": "Item ID 1",
"links": [
"A",
"B",
"C",
"D"
]
},
{
"type": "item",
"name": "Item ID 2",
"links": [
"A",
"E",
"F"
]
}
}
这是d3.js
可视化所必需的,但到目前为止我还无法将其转换。
答案 0 :(得分:1)
以列表形式处理数据:
library(tidyverse)
library(jsonlite)
js <- split(df$links, df$item) %>% # use split to group links by item
imap(~ list(type = "item", name = .y, links = .x)) %>% # add extra fields to each item
{list(items = unname(.))} %>% # add the top level items key
toJSON(auto_unbox = TRUE) # convert to json unbox single element vector to scalar
prettify(js)
{
"items": [
{
"type": "item",
"name": "Item ID 1",
"links": [
"A",
"B",
"C",
"D"
]
},
{
"type": "item",
"name": "Item ID 2",
"links": [
"A",
"E",
"F"
]
}
]
}
将数据操作为data.frame:
js <- df %>%
group_by(item) %>% nest() %>%
mutate(type = "item", data = map(data, "links")) %>%
select(type, name = item, links = data) %>%
list(items = .) %>%
toJSON(dataframe = "rows")
prettify(js)
{
"items": [
{
"type": "item",
"name": "Item ID 1",
"links": [
"A",
"B",
"C",
"D"
]
},
{
"type": "item",
"name": "Item ID 2",
"links": [
"A",
"E",
"F"
]
}
]
}