1

我想将可变大小列表的列表展平为单个数据框。这很容易,除了每个列表可以有不同数量的元素。

这是一个更好地描述问题的示例。有两场音乐会。第一场音乐会有两个乐队。第二场音乐会只有一个乐队。

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

我想将 'concertsList' 展平为如下所示的数据框。

> 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

您的想法将不胜感激。

4

1 回答 1

2
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
于 2013-09-23T14:15:17.660 回答