0

I want to merge two data frames with approximately same number of rows. But the merging needs to be done in a special way.

Suppose the two data frames are A and B. and Ai, Bi represent the ith row of the respective data frames.

Then I want a new dataframe with the following rows:

A1

B1 

A2 

B2 

...

Here is a toy example:

A <- data.frame(col1 = paste("A", 1:5, sep = ""), col2 = rivers[1:5])
B <- data.frame(col1 = paste("B", 1:6, sep = ""), col2 = rivers[1:6])

I want a new data frame C such that

> C

   col1 col2

1    A1  735

6    B1  735

2    A2  320

7    B2  320
...

How do I efficiently do it in R? Please note, there are no empty rows between two rows, as it appears here.

5
  • 3
    Try to take a look at merge function. Pay special attention to Example section of the helpfile. Commented Mar 26, 2014 at 15:17
  • I'm not sure if you actually want to merge. Are there the same columns in A and B?
    – Roland
    Commented Mar 26, 2014 at 15:21
  • 2
    Please post two tiny, representative toy data frames.
    – Henrik
    Commented Mar 26, 2014 at 15:23
  • check out the reshape package? Commented Mar 26, 2014 at 15:27
  • @Roland, The number of columns are same, but one data frame has couple of rows more than the other.
    – user62198
    Commented Mar 26, 2014 at 19:54

1 Answer 1

5

Put them all together, and then resort them:

ord <- order(c(1:nrow(A), 1:nrow(B)))
AB <- rbind(A,B)[ord,]
1
  • 1
    You missing a ) at the end of first line Commented Mar 26, 2014 at 20:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.