将嵌套列表转换为数据框 [英] Converting nested list to dataframe
问题描述
目标是将有时包含丢失记录的嵌套列表转换为数据框架。缺少记录的结构示例是:
The goal is to convert a nested list which sometimes contain missing records into a data frame. An example of the structure when there are missing records is:
str(mylist)
List of 3
$ :List of 7
..$ Hit : chr "True"
..$ Project: chr "Blue"
..$ Year : chr "2011"
..$ Rating : chr "4"
..$ Launch : chr "26 Jan 2012"
..$ ID : chr "19"
..$ Dept : chr "1, 2, 4"
$ :List of 2
..$ Hit : chr "False"
..$ Error: chr "Record not found"
$ :List of 7
..$ Hit : chr "True"
..$ Project: chr "Green"
..$ Year : chr "2004"
..$ Rating : chr "8"
..$ Launch : chr "29 Feb 2004"
..$ ID : chr "183"
..$ Dept : chr "6, 8"
当没有丢失记录时,可以使用数据将列表转换为数据框.frame(do.call(rbind.data.frame,mylist))
。但是,当记录丢失时,会导致列不匹配。我知道有一些功能来合并不匹配列的数据帧,但是我还没有找到可以应用于列表的数据帧。理想的结果将保留所有变量的记录2与NA。希望有一些帮助。
When there are no missing records the list can be converted into a data frame using data.frame(do.call(rbind.data.frame, mylist))
. However, when records are missing this results in a column mismatch. I know there are functions to merge data frames of non-matching columns but I'm yet to find one that can be applied to lists. The ideal outcome would keep record 2 with NA for all variables. Hoping for some help.
编辑添加 dput(mylist)
:
list(structure(list(Hit = "True", Project = "Blue", Year = "2011",
Rating = "4", Launch = "26 Jan 2012", ID = "19", Dept = "1, 2, 4"), .Names = c("Hit",
"Project", "Year", "Rating", "Launch", "ID", "Dept")), structure(list(
Hit = "False", Error = "Record not found"), .Names = c("Hit",
"Error")), structure(list(Hit = "True", Project = "Green", Year = "2004",
Rating = "8", Launch = "29 Feb 2004", ID = "183", Dept = "6, 8"), .Names = c("Hit",
"Project", "Year", "Rating", "Launch", "ID", "Dept")))
推荐答案
您还可以使用(至少v1.9.3) rbindlist
在 data.table
包中:
You can also use (at least v1.9.3) of rbindlist
in the data.table
package:
library(data.table)
rbindlist(mylist, fill=TRUE)
## Hit Project Year Rating Launch ID Dept Error
## 1: True Blue 2011 4 26 Jan 2012 19 1, 2, 4 NA
## 2: False NA NA NA NA NA NA Record not found
## 3: True Green 2004 8 29 Feb 2004 183 6, 8 NA
这篇关于将嵌套列表转换为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!