Breaking up dictionary string into multiple variables in R

2643 views r
3

I was given a data set where the values in a particular variables look like...

{"varname": "value", "varname2": "value2", "varname3": "value3"}

and I want a quick efficient way to break this up into 3 separate variables where the var name is the column name and the values are its corresponding vector. It has to be in R otherwise pythons dictionary functionality would tackle this easily. Any Ideas would be greatly appreciated!

answered question

2 Answers

11

You have a simple json:

library("rjson")
str <- '{"varname": "value", "varname2": "value2", "varname3": "value3"}'
json_data <- fromJSON(str)

The output is:

$`varname`
[1] "value"

$varname2
[1] "value2"

$varname3
[1] "value3"

posted this
2

You can use fromJSON() function from the jsonlite package to parse Python dictionary into R list then convert it to a data frame with as.data.frame(). After that you can access each variable using r_df$...

py_dict <- '{"varname": "value", "varname2": "value2", "varname3": "value3"}'
r_list <- jsonlite::fromJSON(txt = py_dict)
r_df <- as.data.frame(r_list)
r_df

#>   varname varname2 varname3
#> 1   value   value2   value3

Created on 2018-09-16 by the reprex package (v0.2.1)

posted this

Have an answer?

JD

Please login first before posting an answer.