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

361 views Asked by At

I have read

I have a list with unequal columns names which I try to convert to a data frame, with NA for the missing entries in the shorter rows. It is easy with tidyverse (for example with bind_rows), but this is for a low level package that should use base R only.

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))



2

There are 2 answers

0
Ronak Shah On BEST ANSWER

Find out the unique columns in the list, in lapply add the additional columns using 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
0
Sebastian On

use indexes instead of columns and transpose it afterwards

l1 = [1,1]
l2 = [2,2,2,2]

df = pd.DataFrame([l1,l2], index = ('l1', 'l2'))
df.T

#    l1  l2
# 0   1   2
# 1   1   2
# 2 NaN   2
# 3 NaN   2