2013-09-23 2 views
1

가변적 인 크기의 목록을 단일 데이터 프레임으로 병합하고 싶습니다. 이것은 각 목록이 다른 수의 요소를 가질 수 있다는 사실을 제외하면 쉽습니다.R - 데이터 프레임에 대한 목록의 가변 크기 목록을 단순화 하시겠습니까?

다음은 문제를보다 잘 설명하기위한 예입니다. 콘서트가 두 번 있습니다. 첫 번째 콘서트에는 두 개의 밴드가 있습니다. 두 번째 콘서트에는 밴드가 하나뿐입니다.

> 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 

귀하의 생각은 대단히 감사하겠습니다.

답변

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 
관련 문제