我在将json文件转换为数据框时遇到问题。 我将jsonlite和fromJSON()函数与unlist()函数一起使用,但是我无法在所需的数据模型中获取数据。
Json文件的结构如下:
{"JOHN":["AZ","YZ","ZE","ZR","FZ"],"MARK":["FZ","JF","FS"],"LINDA":["FZ","RZ","QF"]}
我想要一个与此类似的数据框:
NAME GROUP
JOHN AZ
JOHN YZ
JOHN ZE
JOHN ZR
JOHN FZ
MARK FZ
MARK JF
MARK FS
...
谢谢!
答案 0 :(得分:2)
我们可以使用fromJSON
中的jsonlite
来获得list
个向量中的key/value
,将其转换为两列数据。使用stack
进行帧重排列并更改列名称(如果需要)。
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
str1 <- '{"JOHN":["AZ","YZ","ZE","ZR","FZ"],"MARK":["FZ","JF","FS"],"LINDA":["FZ","RZ","QF"]}'