如何在r中创建新的键值对

时间:2019-01-07 10:57:00

标签: r json

我有两个数组,周期和计数如下

period <- c("01-12-2017", "01-01-2018", "01-02-2018", "01-03-2018" ,"01-04-2018" ,"01-05-2018")

count <- c(13, 11, 8, 11, 13, 10)

我想要像下面这样的json格式

{"01-12-2017":"13","01-01-2018":"11","01-02-2018":"8","01-03-2018":"11","01-04-2018":"13","01-05-2018":"10"}

2 个答案:

答案 0 :(得分:2)

这可以解决问题(使用软件包jsonlite)

# convert count to character as that is the expected value in desired output
jsonlite::toJSON(as.list(setNames(as.character(count), period)), 
                 auto_unbox = TRUE, pretty = TRUE)
# {
#   "01-12-2017": "13",
#   "01-01-2018": "11",
#   "01-02-2018": "8",
#   "01-03-2018": "11",
#   "01-04-2018": "13",
#   "01-05-2018": "10"
# }

答案 1 :(得分:2)

可以使用paste0(period, ":", count)