Nick Allen
Nick Allen

Reputation: 1467

R - Flatten Variably Sized List of Lists to Data Frame?

I would like to flatten a list of variably-sized lists into a single data frame. This would be easy except for the fact that each list can have a different number of elements.

Here is an example to better describe the problem. There are two concerts. The first concert has two bands. The second concert has only one band.

> concert1 <- list(bands=list(band=list("Foo Fighters","Ace of Base"), venue="concert hall 1"))
> concert2 <- list(bands=list(band=list("The Black Keys"), venue="concert hall 2"))
> concertsList <- list(concert1=concert1, concert2=concert2)

> str(concertsList)
List of 2
 $ concert1:List of 1
  ..$ bands:List of 2
  .. ..$ band :List of 2
  .. .. ..$ : chr "Foo Fighters"
  .. .. ..$ : chr "Ace of Base"
  .. ..$ venue: chr "concert hall 1"
 $ concert2:List of 1
  ..$ bands:List of 2
  .. ..$ band :List of 1
  .. .. ..$ : chr "The Black Keys"
  .. ..$ venue: chr "concert hall 2"

I would like to flatten 'concertsList' into a data frame that would look something like the following.

> data.frame(concert=c("concert1","concert2"), band.1=c("Foo Fighers", "The Black Keys"), band.2=c("Ace of Base", NA), venues=c("concert hall 1", "concert hall 2"))

   concert         band.1      band.2         venues
1 concert1    Foo Fighers Ace of Base concert hall 1
2 concert2 The Black Keys        <NA> concert hall 2

Your thoughts would be much appreciated.

Upvotes: 1

Views: 393

Answers (1)

Roland
Roland

Reputation: 132706

library(plyr)
DF <- as.data.frame(
  do.call(rbind.fill.matrix,
          lapply(concertsList, function(l) {
            res <- unlist(l)
            names(res)[names(res)=="bands.band"] <- "bands.band1"
            t(res)
          })
  )
)

DF$concert <- names(concertsList)
names(DF) <- gsub("bands.","",names(DF))

#           band1       band2          venue  concert
#1   Foo Fighters Ace of Base concert hall 1 concert1
#2 The Black Keys        <NA> concert hall 2 concert2

Upvotes: 2

Related Questions