按组创建列表并创建json

时间:2015-08-31 19:24:38

标签: r

好的,我已经解决了这个问题

combine data in depending on the value of one column

我一直在努力使解决方案适应更复杂的问题,但我无法提供解决方案而不是2列我有3

df <- structure(list(year = c(2000L, 2001L, 2002L, 2003L, 2001L, 2002L), group = c(1L, 1L, 1L, 1L, 2L, 2L), sales = c(20L, 25L, 23L, 30L, 50L, 55L), expenses = c(19L, 19L, 20L, 15L, 27L, 30L)), .Names = c("year", "group", "sales", "expenses"), class = "data.frame", row.names = c(NA, -6L))

    year   group sales  expenses
1   2000     1    20     19
2   2001     1    25     19
3   2002     1    23     20
4   2003     1    30     15
5   2001     2    50     27
6   2002     2    55     30

我需要与第一个问题相同的输出,但不仅仅是销售我还需要在json文件中包含费用

[{"group": 1, "sales":[[2000,20],[2001, 25], [2002,23], [2003, 30]], "expenses":[[2000,19],[2001, 19], [2002,20], [2003, 15]]},
{"group": 2, "sales":[[2001, 50], [2002,55]], "expenses":[[2001, 27], [2002,30]]}] 

1 个答案:

答案 0 :(得分:0)

toJSON(setDT(df1)[, list(sales= paste0('[',toString(sprintf('[%d,%d]',year, sales)),']'),
                     expenses= paste0('[',toString(sprintf('[%d,%d]', year, expenses)),']')), by = group])

试试这个。它与akrun的答案没有什么不同。combine data in depending on the value of one column