1

可変サイズのリストのリストを 1 つのデータ フレームにフラット化したいと考えています。各リストが異なる数の要素を持つことができるという事実を除けば、これは簡単です。

問題をよりよく説明するための例を次に示します。コンサートは2回あります。最初のコンサートは2バンド。2回目のコンサートは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 に答える