1

I am having an issue converting a json file to a data frame. I use jsonlite and fromJSON() function with also unlist() function but I cannot manage to get the data in the data model I want.

Json file is structured this way:

{"JOHN":["AZ","YZ","ZE","ZR","FZ"],"MARK":["FZ","JF","FS"],"LINDA":["FZ","RZ","QF"]}

And I would like to have a data frame similar to this:

NAME GROUP
JOHN  AZ
JOHN  YZ
JOHN  ZE
JOHN  ZR
JOHN  FZ
MARK  FZ
MARK  JF
MARK  FS
...

Thanks !

1 Answer 1

2

We can use fromJSON from jsonlite to get a list of key/value vectors, convert that to a two column data.frame with stack, rearrange the columns and change the column names (if needed).

library(jsonlite)
setNames(stack(fromJSON(str1))[2:1], c("NAME", "GROUP"))
#    NAME GROUP
#1   JOHN    AZ
#2   JOHN    YZ
#3   JOHN    ZE
#4   JOHN    ZR
#5   JOHN    FZ
#6   MARK    FZ
#7   MARK    JF
#8   MARK    FS
#9  LINDA    FZ
#10 LINDA    RZ
#11 LINDA    QF

data

str1 <- '{"JOHN":["AZ","YZ","ZE","ZR","FZ"],"MARK":["FZ","JF","FS"],"LINDA":["FZ","RZ","QF"]}'
Sign up to request clarification or add additional context in comments.

2 Comments

Wow... works like a charm ! Could you just explain me the bracket [2:1] ?
@ML_Enthousiast It is just to rearrange the columns. By default, stack returns the key column second, I changed the column order so that 1st column is 2nd and 2nd first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.