[R] Combinig two data frames

Marc Schwartz MSchwartz at mn.rr.com
Mon Jun 12 11:28:56 CEST 2006


On Mon, 2006-06-12 at 14:44 +0530, Arun Kumar Saha wrote:
> Dear all r-users,
> 
> Suppose I have two data frame:
> 
> A
> 1
> 3
> 4
> 5
> 2
> 
> and
> 
> B
> 5
> 6
> 3
> 5
> 
> Now I want combine this two data frames without losing any value from either
> data frame. More precisely I want to see
> 
>  A    B
> 1   5
> 3   6
> 4   3
> 5   5
> 2   NA
> 
> I tried with cbind function but failed, as it only works when two data
> frames have equal number of rows. Can anyone suggest me any code that can be
> used for any data set?

You can use merge() to do this.  merge() will perform SQL-like joins on
the two data frames.

In this case, we are going to merge A and B, telling merge() to use the
rownames in the two data frames as the basis for matching rows ('by'
argument). 

We also tell it to include all rows ('all' argument) in case some (or
all) of the rownames do not match between the two.

Finally, we take the result of the operation, which by default will
include an additional first column of the rownames themselves and we
delete that column.

> merge(A, B, all = TRUE, by = "row.names")[, -1]
  A  B
1 1  5
2 3  6
3 4  3
4 5  5
5 2 NA

See ?merge for more information.  There are also many variations on its
use that you will find in the list archives.

HTH,

Marc Schwartz



More information about the R-help mailing list