我喜欢将数据从R图表映射到highcharts。我的数据框如下所示:
dput(head(df,10))
structure(list(DATE = structure(c(1362027751, 1362027781, 1362027811,
1362027841, 1362027871, 1362027901, 1362027931, 1362027961, 1362027991,
1362028021), class = c("POSIXct", "POSIXt")), CPU = c(66L, 72L,
69L, 72L, 69L, 68L, 71L, 73L, 63L, 57L)), .Names = c("DATE",
"CPU"), row.names = c(NA, 10L), class = "data.frame")
我正在将此df转换为json格式,如下所示:
ll <- as.list(setNames(df$CPU,df$DATE))
library(RJSONIO)
data<-toJSON(ll)
cat(data, file="data.json")
当我查看teh data.json文件时,它看起来像这样:
{
"2013-02-28 00:02:31": 66,
"2013-02-28 00:03:01": 72,
"2013-02-28 00:03:31": 69,
"2013-02-28 00:04:01": 72,
"2013-02-28 00:04:31": 69,
"2013-02-28 00:05:01": 68,
"2013-02-28 00:05:31": 71,
"2013-02-28 00:06:01": 73,
}
我需要我的data.json文件看起来像这样: [[date,value],[date,value],[date,value]]
[
["2013-02-28 00:02:31": 66],
["2013-02-28 00:03:01": 72],
["2013-02-28 00:03:31": 69],
["2013-02-28 00:04:01": 72]
]
我将如何在R?
中执行此操作答案 0 :(得分:1)
我认为你不想要那个输出。我想您希望将日期和值放在单独的/但是坐标列中:
> ll <- list(as.character(df$DATE), df$CPU)
> data2<-toJSON(ll)
> cat(data2) # You will want to add a 'file=' argument
[
[ "2013-02-27 21:02:31", "2013-02-27 21:03:01", "2013-02-27 21:03:31", "2013-02-27 21:04:01", "2013-02-27 21:04:31", "2013-02-27 21:05:01", "2013-02-27 21:05:31", "2013-02-27 21:06:01", "2013-02-27 21:06:31", "2013-02-27 21:07:01" ],
[ 66, 72, 69, 72, 69, 68, 71, 73, 63, 57 ]
]
看看这个SO Q&amp; A,了解有关问题的HighCharts方面的建议:
(由于R-POSIXct对象的基础表示形式为“double”,因此需要转换为字符的日期时间。)
如果您希望将值分隔为" : "
,我想您可以试试这个,但我认为它不会令人满意:
> ll <- as.list( paste(df$DATE, df$CPU, sep=" : ") )
> data2<-toJSON(ll)
> cat(data2)
[
"2013-02-27 21:02:31 : 66",
"2013-02-27 21:03:01 : 72",
"2013-02-27 21:03:31 : 69",
"2013-02-27 21:04:01 : 72",
"2013-02-27 21:04:31 : 69",
"2013-02-27 21:05:01 : 68",
"2013-02-27 21:05:31 : 71",
"2013-02-27 21:06:01 : 73",
"2013-02-27 21:06:31 : 63",
"2013-02-27 21:07:01 : 57"
]