从数据框在 R 中创建嵌套 key/value 对
Creating a nested key/value pair in R from data frame
我第一次尝试将 csv 转换为 JSON 格式。将csv读入R后,数据帧格式如下:
col1 col2 col3
1 a def1
1 b def2
2 c def3
2 a def1
理想情况下,我想遍历数据框,找到三列的唯一组合,并将 JSON 的 key/value 对分成以下内容:
{ "1":["a", "def1"], ["b", "def2"], "2":["a", "def1"], ["c", "def3"]}
我只能想办法在 python 中实现这个,但我在 R 中执行这个有困难。关于如何开始这个有什么建议吗?
我们可以 split
unname
d 列的子集(没有 'col1')'col1',并在其上应用 toJSON
library(jsonlite)
toJSON(split(unname(df1[-1]), df1$col1))
#{"1":[["a","def1"],["b","def2"]],"2":[["c","def3"],["a","def1"]]}
如果需要order
ed
toJSON(split(unname(df1[do.call(order, df1[1:2]),-1]), df1$col1))
#{"1":[["a","def1"],["b","def2"]],"2":[["a","def1"],["c","def3"]]}
数据
df1 <- structure(list(col1 = c(1L, 1L, 2L, 2L), col2 = c("a", "b", "c",
"a"), col3 = c("def1", "def2", "def3", "def1")), class = "data.frame",
row.names = c(NA,
-4L))
我第一次尝试将 csv 转换为 JSON 格式。将csv读入R后,数据帧格式如下:
col1 col2 col3
1 a def1
1 b def2
2 c def3
2 a def1
理想情况下,我想遍历数据框,找到三列的唯一组合,并将 JSON 的 key/value 对分成以下内容:
{ "1":["a", "def1"], ["b", "def2"], "2":["a", "def1"], ["c", "def3"]}
我只能想办法在 python 中实现这个,但我在 R 中执行这个有困难。关于如何开始这个有什么建议吗?
我们可以 split
unname
d 列的子集(没有 'col1')'col1',并在其上应用 toJSON
library(jsonlite)
toJSON(split(unname(df1[-1]), df1$col1))
#{"1":[["a","def1"],["b","def2"]],"2":[["c","def3"],["a","def1"]]}
如果需要order
ed
toJSON(split(unname(df1[do.call(order, df1[1:2]),-1]), df1$col1))
#{"1":[["a","def1"],["b","def2"]],"2":[["a","def1"],["c","def3"]]}
数据
df1 <- structure(list(col1 = c(1L, 1L, 2L, 2L), col2 = c("a", "b", "c",
"a"), col3 = c("def1", "def2", "def3", "def1")), class = "data.frame",
row.names = c(NA,
-4L))