将 tibble/dataframe 转换为 R 中的 JS 数组

Convert tibble/dataframe to JS array in R

假设您有以下数据:

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',
}

我已经尝试通过此 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-03-25 创建

这够近了吗:

month <- offset$month
names(month) <- offset$index
cat(rjson::toJSON(list(offset = month)))

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