我需要将数据框转换为 R 中的 json 格式。我的数据框 y 是这样的:
dput(y)
structure(list(Name = structure(c(38L, 23L, 16L, 35L, 21L, 6L,
34L, 15L, 46L, 1L, 43L, 28L, 39L, 27L, 7L, 20L, 14L, 44L, 48L,
36L), .Label = c("server09", "server10", "server11", "server12",
"server13", "server14", "server15", "server16", "server17", "server18",
"server19", "server20", "server21", "server22", "server23", "server24",
"server25", "server26", "server27", "server28", "server29", "server30",
"server31", "server32", "server33", "server34", "server35", "server36",
"server37", "server38", "server39", "server40", "server41", "server42",
"server43", "server44", "server45", "server46", "server47", "server48",
"server49", "server50", "server51", "server52", "server53", "server54",
"server55", "server56", "server57", "server58"), class = "factor"),
Date = c(1372737600, 1372737602, 1372737609, 1372737617,
1372737618, 1372737618, 1372737643, 1372737646, 1372737648,
1372737652, 1372737654, 1372737660, 1372737665, 1372737671,
1372737699, 1372737701, 1372737718, 1372737721, 1372737728,
1372737731), Cpu = c(3.9025, 36.3042, 2.6075, 3.1338, 0.9474,
0.149, 5.4401, 2.5652, 0.3612, 3.2651, 1.8703, 13.8967, 4.2438,
5.4401, 2.468, 0.9147, 1.4637, 7.2528, 6.119, 7.7009)), .Names = c("Name",
"Date", "Cpu"), row.names = c(1L, 42L, 83L, 84L, 125L, 126L,
127L, 168L, 169L, 202L, 203L, 236L, 277L, 318L, 359L, 360L, 361L,
362L, 395L, 396L), class = "data.frame")
我需要我的 json 文件看起来像这样:
[{
"name":'server13',
"data": [ [1372737600,3.9025], [1372737602,10], [1372737609,10] ... [1372737731,20] ]
}, {
"name":'server14',
"data": [ [1372737600,4], [1372737602,10], [1372737609,10] ... [1372737731,30] ]
}]
我使用 rjson 包如下:
p <- toJSON(as.list(y))
我得到这个输出:
"{\"Name\":[\"server13\",\"servar14\",...],\"Date\":[1372737600,1372737602,..],\"Cpu\":[3.9025,36.3042,..]}"
有没有一种简单的方法可以在 R 中做到这一点?