我有一个包含超过 1500 个 json 对象的文件,我想在 R 中使用这些对象。我已经能够将数据作为列表导入,但是在将其强制转换为有用的结构时遇到了麻烦。我想创建一个数据框,其中包含每个 json 对象的行和每个键:值对的列。
我用这个小的假数据集重现了我的情况:
[{"name":"Doe, John","group":"Red","age (y)":24,"height (cm)":182,"wieght (kg)":74.8,"score":null},
{"name":"Doe, Jane","group":"Green","age (y)":30,"height (cm)":170,"wieght (kg)":70.1,"score":500},
{"name":"Smith, Joan","group":"Yellow","age (y)":41,"height (cm)":169,"wieght (kg)":60,"score":null},
{"name":"Brown, Sam","group":"Green","age (y)":22,"height (cm)":183,"wieght (kg)":75,"score":865},
{"name":"Jones, Larry","group":"Green","age (y)":31,"height (cm)":178,"wieght (kg)":83.9,"score":221},
{"name":"Murray, Seth","group":"Red","age (y)":35,"height (cm)":172,"wieght (kg)":76.2,"score":413},
{"name":"Doe, Jane","group":"Yellow","age (y)":22,"height (cm)":164,"wieght (kg)":68,"score":902}]
数据的一些特点:
- 这些对象都包含相同数量的键:值对,尽管其中一些值为空
- 每个对象有两个非数字列(名称和组)
- name是唯一标识符,有10个左右的组
- 许多名称和组整体包含空格、逗号和其他标点符号。
基于这个问题:R list(structure(list())) to data frame,我尝试了以下方法:
json_file <- "test.json"
json_data <- fromJSON(json_file)
asFrame <- do.call("rbind.fill", lapply(json_data, as.data.frame))
使用我的真实数据和这个假数据,最后一行给了我这个错误:
Error in data.frame(name = "Doe, John", group = "Red", `age (y)` = 24, :
arguments imply differing number of rows: 1, 0