rlistdataframerbinddo.call

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


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




Solution

  • 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