Subham Chand
Subham Chand

Reputation: 51

how to make a new key value pair in r

I have two arrays, period and count like below

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

and

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

I want it in a format of a json like below

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

Upvotes: 0

Views: 265

Answers (2)

niko
niko

Reputation: 5281

This will do the trick (using the package 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"
# }

Upvotes: 2

B Williams
B Williams

Reputation: 2050

Could use paste0(period, ":", count)

Upvotes: 2

Related Questions