[R] combine the data frames into comma separated list.

Gabor Grothendieck ggrothendieck at gmail.com
Tue Jun 14 02:20:15 CEST 2011


On Mon, Jun 13, 2011 at 5:17 PM, Mary Kindall <mary.kindall at gmail.com> wrote:
> Hi R users,
> I am new to R and am trying to merge data frames in the following way.
> Suppose I have n data frames each with two fields. Field 1 is common among
> data frames but may have different entries. Field 2 is different.
>
>
> Data frame 1:
>
> Src   Target1
> 1        aaa
> 1        bbb
> 1        ccc
> 2        aaa
> 3        ddd
>
>
> Data frame 2:
>
> Src   Target2
> 2        aaaa
> 3        dddd
> 4        bbbb
> 4        eeee
> 4        ffff
>
>
> Data frame 3:
>
> Src   Target3
> 1        xx
> 3        yy
> 5        zz
> 6        tt
> 6        uu
>
> And so on...
>
> I want to convert this into a data frame something similar to:
> Src   Target1                   target2
> target3
> 1      aaa,bbb,ccc            -                                           xx
>
> 2      aaa                        aaaa                                     -
> 3      ddd                        dddd
> yy
> 4      -                            bbbb,eeee,ffff                         -
>
> 5      -
> -                                            zz
> 6      -
> -                                           tt,uu
>
>

Try this where DF1, DF2 and DF3 are the data frames:

L <- list(DF1, DF2, DF3)
merge.all <- function(...) merge(..., all = TRUE)
Reduce(merge.all, lapply(L, function(x) aggregate(x[2], x[1], toString)))

The last line gives this:

  Src       Target1          Target2 Target3
1   1 aaa, bbb, ccc             <NA>      xx
2   2           aaa             aaaa    <NA>
3   3           ddd             dddd      yy
4   4          <NA> bbbb, eeee, ffff    <NA>
5   5          <NA>             <NA>      zz
6   6          <NA>             <NA>  tt, uu


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list