gpt4 book ai didi

r - 使用 R 转换为 JSON(键,值)对

转载 作者:行者123 更新时间:2023-12-02 08:28:37 24 4
gpt4 key购买 nike

我的数据框包含如下数据:

Tester   W1  W2  W3   A   P  WD(%)   TS(Hrs.)   AT(Hrs.)    SU(%) 
a 60 40 102 202 150 100 120 120 100
b 30 38 46 114 150 76 135 120 100
c 25 30 52 107 150 71 120 120 100

通过使用包 jsonlite 我已经转换为 json 格式:

{
"Tester": [ "a", "b", "c" ],
"W1": [ 60, 30, 25],
"W2": [ 40, 38, 30 ],
"W3": [ 102, 46, 52 ],
"A": [ 202, 114, 107 ],
"P": [ 150, 150, 150 ],
"WD...": [ 100, 76, 71 ],
"TS.Hrs..": [ 120, 135, 120 ],
"AT.Hrs..": [ 120, 120, 120 ],
"SU...": [ 100, 100, 100 ]
}

但我的要求是获取像这样的 JSON 格式:

[ {
"Tester":"a"
"W1": 60,
"w2": 40
"w3": 102,
"A": 202
"P": 150,
"WD(%)":100,
"TS (Hrs.) ": 120,
"AT (Hrs.)": 120,
"SU(%)": 100
}]

有人可以帮帮我吗?

最佳答案

当数据集是 list 时,您看到的输出是由 jsonlite 生成的:

library(jsonlite)
toJSON(as.list(head(iris)))

{"Sepal.Length":[5.1,4.9,4.7,4.6,5,5.4],"Sepal.Width":[3.5,3,3.2,3.1,3.6,3.9],"Petal.Length":[1.4,1.4,1.3,1.5,1.4,1.7],"Petal.Width":[0.2,0.2,0.2,0.2,0.2,0.4],"Species":["setosa","setosa","setosa","setosa","setosa","setosa"]}

确保您的数据集确实是一个数据框,您将看到预期的输出:

library(jsonlite)
toJSON(head(iris), pretty = TRUE)

[
{
"Sepal.Length": 5.1,
"Sepal.Width": 3.5,
"Petal.Length": 1.4,
"Petal.Width": 0.2,
"Species": "setosa"
},
{
"Sepal.Length": 4.9,
"Sepal.Width": 3,
"Petal.Length": 1.4,
"Petal.Width": 0.2,
"Species": "setosa"
},
{
"Sepal.Length": 4.7,
"Sepal.Width": 3.2,
"Petal.Length": 1.3,
"Petal.Width": 0.2,
"Species": "setosa"
},
{
"Sepal.Length": 4.6,
"Sepal.Width": 3.1,
"Petal.Length": 1.5,
"Petal.Width": 0.2,
"Species": "setosa"
},
{
"Sepal.Length": 5,
"Sepal.Width": 3.6,
"Petal.Length": 1.4,
"Petal.Width": 0.2,
"Species": "setosa"
},
{
"Sepal.Length": 5.4,
"Sepal.Width": 3.9,
"Petal.Length": 1.7,
"Petal.Width": 0.4,
"Species": "setosa"
}
]

关于r - 使用 R 转换为 JSON(键,值)对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29600943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com