[R] Merging data frames of different length

Gabor Grothendieck ggrothendieck at gmail.com
Sat Dec 20 00:24:15 CET 2008


Try this:

> L <- list(data.frame(A=2, B=3, C=4),
+ data.frame(A=2, B=1, C=3, D=2, E=4, F=5),
+ data.frame(A=1, B=2, C=4, D=3, E=2, F=4, G=5, H=4, I=2))

> library(plyr)
> do.call(rbind.fill, L)
  A B C  D  E  F  G  H  I
1 2 3 4 NA NA NA NA NA NA
2 2 1 3  2  4  5 NA NA NA
3 1 2 4  3  2  4  5  4  2


On Fri, Dec 19, 2008 at 5:48 PM, Dimitri Liakhovitski <ld7631 at gmail.com> wrote:
> Hello, everyone!
>
> I have list L that contains 99 data frames. All data frames have only
> one row, but a different number of columns. Some data frames have 3
> columns, some - 6 columns, and some - 9 columns. The names of the
> first 3 columns are identical in all 99 data frames (e.g., A, B, and
> C). The names of columns 4:6 are identical in data frames that contain
> 6 and 9 columns (e.g., D, E, and F). So that L looks like this:
>
> L[[1]]
> A B C
> 2 3 4
> L[[2]]
> A B C D E F
> 2 1 3 2 4 5
> L[[3]]
> A B C D E F G H I
> 1 2 4 3 2 4 5 4 2
> L[[4]]
> ...
>
>
> How can I merge all of those data frames into one large data frame -
> with 99 rows - such that all data are in the columns with correct
> names. Of course, I'd like the rows of the new large data frame that
> contain the data for less than 9 columns to have NAs in columns 4:9
> (or 7:9).
> In other words, I want the first 3 rows of the new large data frame to
> look like this:
> A B C D E F G H I
> 2 3 4 NA NA NA NA NA NA
> 2 1 3 2 4 5 NA NA NA
> 1 2 4 3 2 4 5 4 2
>
> Ideally, I'd like this merge to work for ANY number of individual
> small data frames in L - even if their total number within L is
> unknown.
>
> I tried merge - but it seems to me that it only works for 2 data
> frames, not for many.
> Thank you very much!
> --
> Dimitri Liakhovitski
> MarketTools, Inc.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list