首页 > 解决方案 > 在 R 中从 json 转换为数据框时出错

问题描述

我正在尝试将我的 json 文件转换为 R 中的数据框,但出现错误。

我做了什么:

 install.packages("rjson")
 # Load the package required to read JSON files.
 library("rjson")
 # Give the input file name to the function.
 result <- fromJSON(file = "myJsonFile.json")
 # Convert JSON file to a data frame.
 json_data_frame <- as.data.frame(result)

我得到的错误是:

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
arguments imply differing number of rows: 2, 1, 8, 4, 9, 7, 0, 3, 37, 5, 104, 6, 17, 14, 102, 
11, 144, 15, 88, 127, 130, 29, 12, 45, 82, 69, 13, 50, 10, 92, 41, 55, 53, 24, 72, 19, 18, 
134, 51, 16, 62, 54, 132, 148, 95, 20, 131, 39, 36, 38, 44, 42, 133, 64, 33, 93, 65, 22, 73, 
63, 85, 57, 135, 46, 110, 91, 43, 173, 81, 49, 71, 21, 32, 136, 28, 84, 31, 99, 149, 126, 52, 
114, 77, 61, 94, 87, 26, 34, 67, 90, 23, 75, 25, 79, 30

我的 json 文件的结构是:

List of 1193
$ 0   : chr [1:2] "e958e6a0-4546-6861-9a40-c3f267675b7e" "26a698a1-855c-f479-984b-60c81f4e1d32"
$ 1   : chr [1:2] "28fb85b7-8b15-bf7a-0fc9-3511d40869b4" "b41afb42-48e3-640a-3ec3-ffb528af182b"
$ 2   : chr "20a8ed50-e592-70e4-aecd-ec17f1723495"...

我有高达 $1192

json文件的一个片段是这样的:

在此处输入图像描述

$0 和 $1 是我的 contig id,大数字是长读 id。我也无法给出列名。请帮忙。

标签: rjsonlistdataframe

解决方案


由于您有不同长度的列表,因此您可以获得最大长度并NA在末尾附加 's。尝试,

n <- 1:max(lengths(result))
out <- do.call(cbind, lapply(result, `[`, n))

推荐阅读