R Tibble / Dataframe到JSON,其中键是第一列?

时间:2018-06-12 09:51:08

标签: r json dataframe tibble

我有一个如下所示的tibble / dataframe:

aspect Col1 Col2            Col3            Col4
ac1    0    2.874891e-05    0.0089479233    -0.0603030498
ac2    0    1.666263e-06    0.0057062434    0
ac3    0    -1.146331e-06   0.0171818879    0
ac4    0    -1.238803e-05   0.0115160832    0
ac5    0    -9.875351e-06   0.0107672657    0
am1    0    -2.851165e-07   0.0005078577    -0.0332858477
am2    0    1.650766e-06    0.0009922302    0.0659597726
am3    0    -2.727834e-06   -0.0002062687   -0.1169132561
am4    0    8.890657e-07    0.0016247214    0.0118325964
am5    0    1.705298e-06    0.0008613693    -0.1069581186

我想创建一个JSON,其中aspect列是“key”,其余列是key:values: col1:value1 col2:value1 ...

我正在尝试使用toJSON和data.frame =“rows”属性,但没有运气。

请告知。

所需的输出应该是这样的:

[{"aspect":"ac1","col1":0,"col2":0,"col3":0.00=
89,"col4":-0.0603}, .....]

2 个答案:

答案 0 :(得分:0)

rjson::toJSON(dat)
[1] "{\"aspect\":[\"ac1\",\"ac2\",\"ac3\",\"ac4\",\"ac5\",\"am1\",\"am2\",\"am3\",\"am4\",\"am5\"],\"Col1\":[0,0,0,0,0,0,0,0,0,0],\"Col2\":[2.874891e-005,1.666263e-006,-1.146331e-006,-1.238803e-005,-9.875351e-006,-2.851165e-007,1.650766e-006,-2.727834e-006,8.890657e-007,1.705298e-006],\"Col3\":[0.0089479233,0.0057062434,0.0171818879,0.0115160832,0.0107672657,0.0005078577,0.0009922302,-0.0002062687,0.0016247214,0.0008613693],\"Col4\":[-0.0603030498,0,0,0,0,-0.0332858477,0.0659597726,-0.1169132561,0.0118325964,-0.1069581186]}"

答案 1 :(得分:0)

大约有3个主要的JSON包: jsonlite, rjson, RJSONIO

使用jsonlite解决了我的问题:jsonlite::toJSON(data)

但您可以使用属性dataframe = "rows"来改变它的行为。

它帮助了我,所以传播给别人:)