我在将R数据帧或表的数据格式化为所需的JSON文件时遇到麻烦。
这是我想要的格式。
{ "PercentileFromR":
[ "499 to 516", "517 to 534", "535 to 552", "553 to 569", "570 to 586", "587 to 604", "605 to 622"],
[ "0", "7", "38", "124", "271", "388", "442"],
[ "4", "6", "35", "68", "81", "71", "33"]
]
}
我的代码是
col1 <- c("499 to 516","517 to 534","535 to 552","553 to 569","570 to 586","587 to 604","605 to 622")
col2 <- c("0","7","38","124","271","388","442")
col3 <- c("4","6","35","68","81","71","33")
tableData <- rbind(col1, col2, col3)
install.packages('jsonlite', dependencies=TRUE, repos='http://cran.rstudio.com/')
library(jsonlite)
exportJSON <- toJSON(tableData, pretty = TRUE)
write(exportJSON, "output.json")
但这就是我得到的
[
["499 to 516", "517 to 534", "535 to 552", "553 to 569", "570 to 586", "587 to 604", "605 to 622"],
["0", "7", "38", "124", "271", "388", "442"],
["4", "6", "35", "68", "81", "71", "33"]
]
我能够做到这一点,但它仍然不是我想要的格式:
{"binCategories":"499 to 516","plot1binCount":"0","plot2binCount":"4","NA":"517 to 534","NA":"7","NA":"6","NA":"535 to 552","NA":"38","NA":"35","NA":"553 to 569","NA":"124","NA":"68","NA":"570 to 586","NA":"271","NA":"81","NA":"587 to 604","NA":"388","NA":"71","NA":"605 to 622","NA":"442","NA":"33"}
答案 0 :(得分:1)
在将数据框转换为JSON之前将其转换为命名列表:
.trigger("owl.prev");
答案 1 :(得分:0)
您可以使用带有某些正则表达式的exportJSON
来操纵gsub
对象:
exportJSON <- gsub("\\[\n", "\\{ \"PercentileFromR\":\n", exportJSON)
exportJSON <- gsub("\n\\]", "\n\\]\n\\}", exportJSON)
exportJSON
输出为:
{ "PercentileFromR":
["499 to 516", "517 to 534", "535 to 552", "553 to 569", "570 to 586", "587 to 604", "605 to 622"],
["0", "7", "38", "124", "271", "388", "442"],
["4", "6", "35", "68", "81", "71", "33"]
]
}