【问题标题】:Convert tibble/dataframe to JS array in R在 R 中将 tibble/dataframe 转换为 JS 数组
【发布时间】:2021-06-22 13:17:53
【问题描述】:

假设你有以下数据:

library(tibble)

offset <- tribble(
  ~index, ~month,
  0, "Jul",
  1, "Aug",
  2, "Sep",
  3, "Oct"
)

如何将offset 转换为以下 JavaScript 友好数组?

'offset': {
  0: 'Jul',
  1: 'Aug',
  2: 'Sep',
  3: 'Oct',
}

我尝试通过post 使用library(jsonlite),但它没有提供预期的结果:

library(jsonlite)

toJSON(offset)
#> [{"index":0,"month":"Jul"},{"index":1,"month":"Aug"},{"index":2,"month":"Sep"},{"index":3,"month":"Oct"}]

toJSON(offset, dataframe = "rows")
#> [{"index":0,"month":"Jul"},{"index":1,"month":"Aug"},{"index":2,"month":"Sep"},{"index":3,"month":"Oct"}]

toJSON(offset, dataframe = "columns")
#> {"index":[0,1,2,3],"month":["Jul","Aug","Sep","Oct"]}

toJSON(offset, dataframe = "values")
#> [[0,"Jul"],[1,"Aug"],[2,"Sep"],[3,"Oct"]]

我在 JavaScript 方面的经验非常有限,因此非常感谢任何帮助!

reprex package (v1.0.0) 于 2021 年 3 月 25 日创建

【问题讨论】:

    标签: javascript r json jsonlite


    【解决方案1】:

    这够近了吗:

    month <- offset$month
    names(month) <- offset$index
    cat(rjson::toJSON(list(offset = month)))
    
    {"offset":{"0":"Jul","1":"Aug","2":"Sep","3":"Oct"}}
    

    【讨论】:

    • 太棒了!谢谢!
    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 2021-07-23
    • 2021-10-06
    • 2018-01-12
    • 2016-07-30
    • 2021-12-10
    • 1970-01-01
    • 2017-08-10
    相关资源
    最近更新 更多