2

我第一次尝试将 csv 转换为 JSON 格式。当 csv 被读入 R 时,它的数据帧格式如下:

col1   col2   col3
1       a      def1
1       b      def2
2       c      def3
2       a      def1

理想情况下,我想遍历数据框,找到三列的唯一组合,并将 JSON 的键/值对分成以下内容:

{ "1":["a", "def1"], ["b", "def2"], "2":["a", "def1"], ["c", "def3"]}

我只能想办法在 python 中实现这一点,但我在 R 中执行它时遇到了困难。关于如何开始这个有什么建议吗?

4

1 回答 1

1

我们可以通过 'col1' 列splitunnamed 子集(没有 'col1'),并应用toJSON

library(jsonlite)
toJSON(split(unname(df1[-1]), df1$col1))
#{"1":[["a","def1"],["b","def2"]],"2":[["c","def3"],["a","def1"]]} 

如果需要order编辑

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))
于 2020-06-09T00:12:43.803 回答