I'm trying to parse some bizarre data structures I've encountered during my travels. Essentially they resemble python or javascript dictionaries, but both the key and the value are numeric:
weird <- "{47=4578.0005, 181=23456.7831, 216=7548.2367}"
In the hopes of converting this to a table, I tried transforming it into a more typical dictionary format and parsing it using jsonlite
:
library(tidyverse)
library(jsonlite)
weird <- parse_json(str_replace(weird, "=", ":"))
#> Error: parse error: invalid object key (must be a string)
The parse_json
function rightfully complains that the key isn't a string. I can certainly dissect all of this using str_split
, but I was hoping a kind soul might have some insight into a more elegant/compact solution (hopefully avoiding regex altogether) that could parse this into a table as such:
tibble::tribble(
~ key, ~ value,
47, 4578.0005,
181, 23456.7831,
216, 7548.2367
)
#> # A tibble: 3 x 2
#> key value
#> <dbl> <dbl>
#> 1 47 4578.
#> 2 181 23457.
#> 3 216 7548.
Thanks!