我如何将这个csv与D3-ready json争论?

时间:2016-04-15 04:49:45

标签: json r

我正在构建一个stacked column chart并尝试找出转换我的CSV数据的最简洁方法:

data <-   "apples oranges grapes
    5 10 22 
    4 12 28 
    2 19 32
    7 23 35
    23 17 43"
fruits <- read.table(text=data, header=TRUE)

进入多维JSON:

var dataset = [  
       //apples
        [
                { x: 0, y: 5 },
                { x: 1, y: 4 },
                { x: 2, y: 2 },
                { x: 3, y: 7 },
                { x: 4, y: 23 }
        ], //oranges
        [
                { x: 0, y: 10 },
                { x: 1, y: 12 },
                { x: 2, y: 19 },
                { x: 3, y: 23 },
                { x: 4, y: 17 }
        ], // grapes
        [
                { x: 0, y: 22 },
                { x: 1, y: 28 },
                { x: 2, y: 32 },
                { x: 3, y: 35 },
                { x: 4, y: 43 }
        ]
];

我可以使用rson的{​​{1}}来获取基本数组:

toJSON

但是我无法理解如何将其转换为我实际需要的格式。我很高兴在JavaScript中进行转换,如果这更直接,但我想弄清楚如何在R中进行转换。

1 个答案:

答案 0 :(得分:0)

我们可以通过list行序列创建data.frame cbindMap个&#39;水果&#39; (使用list),使用&#39; fruits&#39;列名称设置toJSON的名称,并使用jsonlite中的library(jsonlite) toJSON(setNames(Map(function(x,y) data.frame(x,y), list(1:nrow(fruits)), fruits), names(fruits))) {"apples": [ {"x":1,"y":5}, {"x":2,"y":4}, {"x":3,"y":2}, {"x":4,"y":7}, {"x":5,"y":23} ],"oranges": [ {"x":1,"y":10}, {"x":2,"y":12}, {"x":3,"y":19}, {"x":4,"y":23}, {"x":5,"y":17} ],"grapes": [ {"x":1,"y":22}, {"x":2,"y":28}, {"x":3,"y":32}, {"x":4,"y":35}, {"x":5,"y":43} ]}

GET /cars?ids=1,2,3,4,5