user62198
user62198

Reputation: 1874

Merging two data frames in R

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.

Upvotes: 0

Views: 280

Answers (1)

Gavin Kelly
Gavin Kelly

Reputation: 2414

Put them all together, and then resort them:

ord <- order(c(1:nrow(A), 1:nrow(B)))
AB <- rbind(A,B)[ord,]

Upvotes: 5

Related Questions