0

我喜欢将数据从 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")

当我查看 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 中做到这一点?

4

1 回答 1

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&A 以获得有关问题的 HighCharts 方面的建议:

Highcharts JSON 加载问题

(需要将日期时间转换为字符,因为 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" 
]
于 2013-06-07T14:51:50.243 回答