如何使用数据框和列名作为参数从R函数创建自定义json输出

时间:2014-09-10 16:14:28

标签: r rjson

我需要创建和R函数,它将数据框和列名作为参数(参数列表中应该至少有两个列名,可能还有更多)。然后给定数据框,我需要根据给定的列名创建一个json格式的输出。例如,

这是我的df:

structure(list(DateTime = structure(1:8, .Label = c("8/24/2014 15:20", 
"8/24/2014 15:55", "8/24/2014 16:04", "8/24/2014 16:18", "8/24/2014 16:27", 
"8/24/2014 16:42", "8/24/2014 16:56", "8/24/2014 17:10"), class = "factor"), 
    Server1 = c(6.09, 4.54, 5.03, 4.93, 6.27, 4.59, 5.91, 4.53
    ), Server2 = c(5.7, 4.38, 4.52, 4.61, 4.18, 4.61, 4.37, 4.3
    ), Server3 = c(5.21, 5.33, 4.92, 5.56, 5.62, 6.73, 4.76, 
    4.59)), .Names = c("DateTime", "Server1", "Server2", "Server3"
), class = "data.frame", row.names = c(NA, -8L))

我需要此函数来返回此输出:

[{"name":"Server1","data":[[18/24/2014 15:20,6.09],[8/24/2014 15:55,4.54],[8/24/2014 16:04,5.03]]},
{"name":"Server2","data":[[18/24/2014 15:20,7.7],[8/24/2014 15:55,4.38],[8/24/2014 16:04,4.52]]},
{"name":"Server3","data":[[18/24/2014 15:20,5.21],[8/24/2014 15:55,5.33],[8/24/2014 16:04,4.92]]}]

我是如何从这开始的?

1 个答案:

答案 0 :(得分:2)

假设您的数据框名为dd,那么

library(rjson)
library(reshape2)

mm <- melt(dd)
ss <- split(mm, mm$variable)

poo <- unname(Map(function(n,x) 
    list(name=n, data=unname(lapply(split(x, 1:nrow(x)), function(x) {
        list(x$DateTime, x$value)
}))), names(ss),ss))
cat(toJSON(poo))

这就是

[{"name":"Server1","data":[["8/24/2014 15:20",6.09],["8/24/2014 15:55",4.54],["8/24/2014 16:04",5.03],["8/24/2014 16:18",4.93],["8/24/2014 16:27",6.27],["8/24/2014 16:42",4.59],["8/24/2014 16:56",5.91],["8/24/2014 17:10",4.53]]},
{"name":"Server2","data":[["8/24/2014 15:20",5.7],["8/24/2014 15:55",4.38],["8/24/2014 16:04",4.52],["8/24/2014 16:18",4.61],["8/24/2014 16:27",4.18],["8/24/2014 16:42",4.61],["8/24/2014 16:56",4.37],["8/24/2014 17:10",4.3]]},
{"name":"Server3","data":[["8/24/2014 15:20",5.21],["8/24/2014 15:55",5.33],["8/24/2014 16:04",4.92],["8/24/2014 16:18",5.56],["8/24/2014 16:27",5.62],["8/24/2014 16:42",6.73],["8/24/2014 16:56",4.76],["8/24/2014 17:10",4.59]]}]

似乎与你想要的相符。 它并不是非常漂亮,因为你真的不遗余力地以一种rsjon不一定喜欢的方式重塑你的数据。