我想将一个可变大小的列表列表压缩成一个数据帧。除了每个列表可以具有不同数量的元素之外,这很容易。
以下是更好地描述问题的示例。有两场音乐会。第一场音乐会有两支乐队。第二场音乐会只有一支乐队。
> 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
非常感谢您的想法。
答案 0 :(得分: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