【发布时间】:2014-05-08 06:31:05
【问题描述】:
是否有一种干净的方法可以将 data.frames 上的默认“/json”后缀选项更改为基于列而不是基于行?
如果我理解正确,R 中的 Data.frames 实际上只是命名列表,其中每个列表的长度与其他列表相同。使用jsonlite,很容易看出区别(小例子,是的):
library(jsonlite)
ll <- list(xx=1:3, yy=6:8)
dd <- data.frame(xx=1:3, yy=6:8)
toJSON(dd)
# [1] "[ { \"xx\" : 1, \"yy\" : 6 }, { \"xx\" : 2, \"yy\" : 7 }, { \"xx\" : 3, \"yy\" : 8 } ]"
toJSON(ll)
# [1] "{ \"xx\" : [ 1, 2, 3 ], \"yy\" : [ 6, 7, 8 ] }"
toJSON(dd, dataframe='column')
# [1] "{ \"xx\" : [ 1, 2, 3 ], \"yy\" : [ 6, 7, 8 ] }"
toJSON(as.list(dd))
# [1] "{ \"xx\" : [ 1, 2, 3 ], \"yy\" : [ 6, 7, 8 ] }"
最后三个是相同的。通过使用toJSON 的dataframe 参数或将data.frame 强制转换为list,很容易强制它看起来相同。
使用 OpenCPU 的 API,调用看起来很相似:
$ curl http://localhost:7177/ocpu/library/base/R/list/json -H "Content-Type: application/json" -d '{ "xx":[1,2,3], "yy":[6,7,8] }'
{
"xx" : [
1,
2,
3
],
"yy" : [
6,
7,
8
]
}
$ curl http://localhost:7177/ocpu/library/base/R/data.frame/json -H "Content-Type: application/json" -d '{ "xx":[1,2,3], "yy":[6,7,8] }'
[
{
"xx" : 1,
"yy" : 6
},
{
"xx" : 2,
"yy" : 7
},
{
"xx" : 3,
"yy" : 8
}
]
如果我希望 data.frame 本身基于 JSON 化列,那么我需要将其强制转换为 list:
$ curl http://localhost:7177/ocpu/library/base/R/data.frame -H "Content-Type: application/json" -d '{ "xx":[1,2,3], "yy":[6,7,8] }'
/ocpu/tmp/x000a0fb8/R/.val
/ocpu/tmp/x000a0fb8/stdout
/ocpu/tmp/x000a0fb8/source
/ocpu/tmp/x000a0fb8/console
/ocpu/tmp/x000a0fb8/info
$ curl http://localhost:7177/ocpu/library/base/R/as.list/json -d "x=x000a0fb8"
{
"xx" : [
1,
2,
3
],
"yy" : [
6,
7,
8
]
}
三个问题:
有没有办法将 OpenCPU 自动 JSON 化的默认行为更改为基于列?
是否存在默认为基于行的原因(除了“必须默认设置”之外)? (这样我可以更好地理解基础和效率,而不是挑战。)
不过,这都是学术性的,因为大多数(如果不是全部)接受 JSON 输出的库都会透明地理解和转换格式。对吧?
(Win7 x64, R 3.0.3, opencpu 1.2.3, jsonlite 0.9.4)
(PS:谢谢,Jeroen,OpenCPU 太棒了!我玩的越多,我就越喜欢。)
【问题讨论】: