如何将列表转换为具有不相等列名的数据框,仅基于 R

How to cast a list to a data frame with unequal columns names, base R only

我已阅读

我有一个列名不相等的列表,我尝试将其转换为数据框,较短行中缺少的条目使用 NA。使用 tidyverse 很容易(例如使用 bind_rows),但这是针对应仅使用基础 R 的低级包。

mylist = list(
  list(a = 3, b = "anton"),
  list(a = 5, b = "bertha"),
  list(a = 7, b = "caesar", d = TRUE)
)
# No problem with equal number of columns
do.call(rbind, lapply(mylist[1:2], data.frame))

# The list of my names
unique(unlist(lapply(mylist, names)))

# rbind does not like unequal numbers
do.call(rbind, lapply(mylist, data.frame))



找出列表中唯一的列,在lapply中使用setdiff添加额外的列。

cols <- unique(unlist(sapply(mylist, names)))

do.call(rbind, lapply(mylist, function(x) {
  x <- data.frame(x)
  x[setdiff(cols, names(x))] <- NA
  x
}))

#  a      b    d
#1 3  anton   NA
#2 5 bertha   NA
#3 7 caesar TRUE