简体   繁体   English

将R数据帧写入信息报可读的JSON文件

[英]Writing an R dataframe into an infogram readable JSON file

I'm trying to write a dataframe to a JSON format that infogram can recognise, to automate live updates. 我正在尝试将数据框写入Infogram可以识别的JSON格式,以实现实时更新的自动化。 I've been using R and the jsonlite package. 我一直在使用R和jsonlite包。

For example: 例如:

df <- data.frame(X = c(1,2,3),
                 Y = c(5,7,8))
df

#  X Y
#1 1 5
#2 2 7
#3 3 8

I've come up with: 我想出了:

require(jsonlite)

rbind(as.matrix(t(names(df))), 
      as.matrix(df)) %>% 
  toJSON(pretty = T) # or write_json(filename, pretty = T) to write straight to file

Which results in: 结果是:

[
  ["X", "Y"],
  ["1", "5"],
  ["2", "7"],
  ["3", "8"]
] 

The desired format is essentially the above but enclosed in an extra pair of square brackets (note the first array consists of column headings, then each subsequent array is an observation). 所需的格式本质上是上述格式,但用一对额外的方括号括起来(请注意,第一个数组由列标题组成,然后每个后续数组都是一个观察值)。

[[
  ["X", "Y"],
  ["1", "5"],
  ["2", "7"],
  ["3", "8"]
]]

Is there an easy way to achieve this? 有没有简单的方法可以做到这一点? Thanks 谢谢

require(jsonlite)

## The data.frame
df <- data.frame(X = c(1,2,3),
                 Y = c(5,7,8))

Now you could modify your object to be a list then you'll get the same list item in your json output: 现在您可以将对象修改为列表,然后在json输出中获得相同的列表项:

mat <- list(rbind(as.matrix(t(names(df))), as.matrix(df)))

now with the extra bracket you want: 现在有了您想要的额外括号:

toJSON(mat, pretty = T)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM